我正在创建一个小的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;
任何和所有帮助表示赞赏!
将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完全脱钩了;易于在其他应用程序中重用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句