2017-08-11 20 views
2

私は小さなVueプラグインを作成しています。ユーザーは任意のコンポーネント内から「ページ通知」を追加できます。私は正常のようなものを実装しました:Vueプラグインの一部としてVuexストアに突然変異を追加する

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のdocsにある "Dynamic Module Registration"のドキュメントを見つけました:https://vuex.vuejs.org/en/modules.html#dynamic-module-registration –

関連する問題