Adding Mutations to Vuex store as part of Vue Plugin

雨燕双飞 提交于 2020-01-24 04:19:04

问题


I'm creating a small Vue Plugin that allows a user to add a "page notification" from within any component. I've successfully implemented something like:

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

And it works! But I've had to register the mutations and actions required for my plugin to work as part of the file that sets up the rest of the store for my app:

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

Is there a way to add actions and mutations to my store from within my plugin? It currently looks like this:

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;

Any and all help appreciated!


回答1:


Import vuex store into your plugin; make it hard to reuse. You should put dependences in plugin options.

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

Now your plugin total decouple with vuex; easy to reuse in other application.



来源:https://stackoverflow.com/questions/45644171/adding-mutations-to-vuex-store-as-part-of-vue-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!