【问题标题】:Adding Mutations to Vuex store as part of Vue Plugin作为 Vue 插件的一部分,将突变添加到 Vuex 存储
【发布时间】:2018-01-20 12:01:20
【问题描述】:

我正在创建一个小型 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;

感谢您的任何帮助!

【问题讨论】:

    标签: javascript vue.js vuejs2 vuex


    【解决方案1】:

    将 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
         }
    }
    

    现在你的插件与 vuex 完全解耦了;易于在其他应用程序中重用。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-19
    • 2018-02-04
    • 2021-09-02
    • 2018-05-24
    • 1970-01-01
    • 2021-01-20
    • 2020-10-31
    • 1970-01-01
    相关资源
    最近更新 更多