2017-08-11 17 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 –