作为Vue插件的一部分,将变异添加到Vuex商店

Dan*_*own 5 javascript vue.js vuex vuejs2

我正在创建一个小的Vue插件,允许用户在任何组件中添加"页面通知".我成功实现了类似的东西:

this.$notifications.add("a message");

它的工作原理!但是我必须注册我的插件所需的突变和操作,作为为我的应用设置商店其余部分的文件的一部分:

export default new Vuex.Store({...})

有没有办法从我的插件中添加动作和突变到我的商店?它目前看起来像这样:

import vuex from './../store';

const MyPlugin = {

  install(Vue, options) {

    // 4. add an instance method
    Vue.prototype.$notifications =
    {
      notificationTypes: {
          0: "warning",
          1: "info"
      },
      add: function (options) {

        let id = "page-notification-" + (vuex.state.pageNotificationsCreated + 1);
        let message = options.message || options || "no message";
        let notificationType = this.notificationTypes[0];

        if(options.notificationType && Number.isInteger(options.notificationType)){
            // Map int to string type
            notificationType = this.notificationTypes[options.notificationType] || notificationType;
        }else{
            // Or use string we were provided ;)
            notificationType = options.notificationType;
        }

        let notification = { id: id, message: message, notificationType: notificationType };
        vuex.dispatch('addNotification', notification);
      }
    }

  }
};

export default MyPlugin;
Run Code Online (Sandbox Code Playgroud)

任何和所有帮助表示赞赏!

Gia*_*yen 14

将vuex商店导入您的插件; 使重复使用变得困难.你应该把依赖放在插件选项中.

const MyPlugin = {
     install(vue, { store }){ // now your plugin depend on store
          if (!store) {
               throw new Error("Please provide vuex store.");
          }
          // register your own vuex module 
          store.registerModule({states, mutations, actions });

          // hook vue
     }
}
Run Code Online (Sandbox Code Playgroud)

现在你的插件与vuex完全分离; 易于在其他应用程序中重用.