programing

Vue 플러그인의 일부로 Vuex 저장소에 돌연변이 추가

coolbiz 2022. 9. 28. 23:03
반응형

Vue 플러그인의 일부로 Vuex 저장소에 돌연변이 추가

사용자가 컴포넌트 내에서 "페이지 알림"을 추가할 수 있는 작은 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와 분리되므로 다른 애플리케이션에서 쉽게 재사용할 수 있습니다.

언급URL : https://stackoverflow.com/questions/45644171/adding-mutations-to-vuex-store-as-part-of-vue-plugin

반응형