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!
Actions are similar to mutations, the differences being that: Instead of mutating the state, actions commit mutations. Actions can contain arbitrary asynchronous operations.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With