【问题标题】:Use Vue.js plugin in Vuex Store module在 Vuex Store 模块中使用 Vue.js 插件
【发布时间】:2018-05-06 12:07:39
【问题描述】:

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

在一个组件中,我可以这样称呼它:this.$plugin()。但是,在 模块 中,this 未设置。我认为Vue.$plugin() 会起作用,因为我使用Vue.use(plugin)Vue 作为全局变量来初始化插件,但事实并非如此。

如何从模块中引用插件?

【问题讨论】:

  • 是你的插件吗?你有密码吗?
  • 这里是插件:github.com/euvl/vue-notification 尝试使用this.$notify()。但这应该适用于所有具有实例方法的插件。
  • 使用this肯定不行,Vuex不是Vue的实例。查看插件,它看起来并没有为您提供一种简单的方法来做您想做的事情。
  • 这是hacky way,您可以这样做。但我认为您可能希望在 Vuex 状态下创建一个通知数组,并在需要通知时填充它,然后在 Vue 中观察通知队列并根据需要弹出/显示它们。
  • 这就是我最终的做法。 window._app = new Vue({});_app.$notify({}); 感谢您的帮助!

标签: vue.js vuex


【解决方案1】:

Bert 在此处提供的示例中回答了此问题: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 }
    })

【讨论】:

    【解决方案2】:

    将 vue 实例作为参数传入

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

    // Vue component
    {
      methods: {
        const vm = this
        this.$store.dispatch('someaction', { vm })
      }
    }
    
    // Store action
    {
      someaction (context, { vm }) {
        vm.$dialog.alert('Something went wrong')
      }
    }
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 这行得通,谢谢。我只是想知道:我们不创建一种“双重导入”:vue 导入模块,模块导入 vue?
      • @massimoi,我不这么认为。循环导入会导致很多问题,但在 Vue 中导入它是很常见的,以便注册插件或使用它的扩展功能。
      猜你喜欢
      • 2018-11-23
      • 2021-11-22
      • 1970-01-01
      • 2020-05-14
      • 2018-09-15
      • 2021-05-05
      • 2021-08-27
      • 2023-03-11
      • 2020-06-06
      相关资源
      最近更新 更多