在 Vuex Store 模块中使用 Vue.js 插件

Use Vue.js plugin in Vuex Store module

我正在尝试在 Vuex 商店模块中使用 Vue.js 插件。

组件中,我可以这样调用它:this.$plugin()。但是,在 模块 中,未设置 this。我认为 Vue.$plugin() 会工作,因为我使用 Vue.use(plugin)Vue 作为全局变量初始化插件,但它没有。

如何从模块引用插件?

此问题已由 Bert in the example provided here: https://codesandbox.io/s/jp4xmzl0xy

回答
    import Vue from 'vue'
    import App from './App'
    import Notifications from 'vue-notification'
    import Vuex from "vuex"
    Vue.use(Notifications)
    Vue.use(Vuex)
    
    let notifier = new Vue()
    
    
    const store = new Vuex.Store({
      state:{},
      actions:{
        notify(context, payload){
          notifier.$notify(payload)
        }
      }
    })
    
    
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      store,
      template: '<App/>',
      components: { App }
    })

我发现的最干净的方法是在 store/module 中导入 Vue,然后通过 Vue 原型使用​​插件。

import Vue from 'vue';

// .. in some logic
Vue.prototype.$dialog.alert('Something went wrong');

将 vue 实例作为参数传入

另一种选择是将 vue 实例作为您的操作的参数传递。

// Vue component
{
  methods: {
    const vm = this
    this.$store.dispatch('someaction', { vm })
  }
}

// Store action
{
  someaction (context, { vm }) {
    vm.$dialog.alert('Something went wrong')
  }
}

我发现了其他几种方法。老实说,不确定哪个是最好的。我真的不喜欢导入 Vue 和调用原型方法。似乎是一个完整的反模式,并且在使用 localVue 进行测试时特别困难,因为操作已耦合到全局 Vue。

  1. 我很确定你不应该这样做但是你可以使用[=从一个动作中访问商店的vue实例13=]

  2. 您可以创建商店插件:

const notifyStore = (store) => {
  store.$notify = store._vm.$notify
}
  1. 将通知创建为独立模块
import Vue from 'vue'

let notifier = new Vue()

export default notifier
  1. 两者的结合
import notifier from './notifier'

const notifyStorePlugin = (store) => {
  store.$notify = notifier.$notify
}

我并不是说这是 的最终答案。我也非常愿意接受反馈和其他建议。