2017-08-11 49 views
2

我创建了一个小Vue插件,允许用户从任何组件中添加“页面通知”。我已经成功地实现类似:向Vue存储添加突变作为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; 

任何和所有的帮助赞赏!

回答

4

将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;易于在其他应用程序中重用。

+0

谢谢!感兴趣的是,在阅读了这个答案之后,我在Vuex文档中找到了“Dynamic Module Registration”的文档:https://vuex.vuejs.org/en/modules.html#dynamic-module-registration –