programing

Vue 플러그인 설치 기능에 Vuex를 추가하고 구성 요소 간에 상태를 공유하는 방법이 있는가?

prostudy 2022. 5. 15. 23:43
반응형

Vue 플러그인 설치 기능에 Vuex를 추가하고 구성 요소 간에 상태를 공유하는 방법이 있는가?

기본적으로 vue 설치 및 vue 구성 요소에서 vue 플러그인을 통해 추가되는 내 스토어를 사용하고 싶다.

실제 설치 기능 내에서 vuex를 사용할 수 있고 vuex가 할 수 있는 모든 작업을 수행할 수 있다는 것을 발견했지만, 사용자 지정 구성 요소에 전달할 수는 없는 것 같아.

내 SFC에 글로벌 이벤트를 추가하는 다른 방법은 없으십니까?

import MyComponent from './MyComponent.vue'
import MySecondComponentfrom './MySecondComponent.vue'
import Vuex from 'vuex'
import store from './store.js'

const CustomFn = function(message, options) {
    this.$store.dispatch("someRandomAction", { message, options })
}

export default {
    install(Vue, options) {
        if (this.installed) { return }
        this.installed = true

        Vue.use(Vuex)

        const storeInstance = new Vuex.Store(store)

        Vue['store'] = storeInstance

        // is there a way to add storeInstance to my own components and share one state between them?
        Vue.component('MyComponent', Vue.extend(MyComponent))
        Vue.component('MySecondComponent', Vue.extend(MySecondComponent))

        Vue.prototype['$doStuff'] = CustomFn
        Vue['doStuff'] = CustomFn
    }
}

문제는 MyComponent 내에서 이 Vuex 스토어 인스턴스를 통과하지 못하고 여러 구성 요소 간에 동일한 스토어를 공유할 수 없다는 점이다.

사용자 지정 구성 요소 속성은 Vue 2에 할당하여 전체적으로 제공되어야 함Vue.prototype구성요소 인스턴스(instance)는 그것으로부터 원형적으로 상속되기 때문이다.

new Vuex.Store(store)에 대한 실수다.store이미 Vuex 저장소가 있으며 저장소 옵션을 포함하는 일반 개체가 아님.이것은 이 질문에서 보이는 것과 같이 상점을 오작동하게 할 것이다.라 할지라도store아직 저장 인스턴스가 아니므로, 인스턴스를 하나의 인스턴스로 만들어 별도 모듈로 내보내는 것이 타당하여, 비 컴포넌트 모듈로 가져올 수 있다.

다음과 같아야 한다.

Vue.prototype.$store = store

참조URL: https://stackoverflow.com/questions/70816511/is-there-a-way-to-add-vuex-to-vue-plugin-install-function-and-share-state-betwee

반응형