Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Mutations to Vuex store as part of Vue Plugin

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!

like image 840
Daniel Brown Avatar asked Aug 11 '17 21:08

Daniel Brown


People also ask

What is the difference between Vuex mutations and actions?

Actions are similar to mutations, the differences being that: Instead of mutating the state, actions commit mutations. Actions can contain arbitrary asynchronous operations.

How would you commit a mutation from another module Vuex?

To change another module state from one module in Vuex, we can call commit with the mutation name with the root option set to true . commit("TOGGLE_LOADING", null, { root: true }); to call commit to commit the TOGGLE_LOADING mutation with root set to true .


1 Answers

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.

like image 82
Giap Nguyen Avatar answered Sep 20 '22 03:09

Giap Nguyen