programing

여러 번의 Vuex 변환 구독 트리거

lovejava 2023. 6. 13. 21:53

여러 번의 Vuex 변환 구독 트리거

vue CLI를 사용하고 있으며 여러 구성 요소를 생성했습니다.

부가가치

import home_tpl from './home.vue';

new vue({
    el : '#app',
    components : { home_tpl },
    created(){
        this.$store.subscribe((mutation) => {
            switch(mutation.type){
                case 'listing':
                    alert();
                break;
        });
    }
})

그리고 집에도 청취자가 있습니다.가치관

가정적 가치

export default{
    created(){
        this.$store.subscribe((mutation) => {
            switch(mutation.type){
                case 'listing':
                    alert();
                break;
        });
    }
}

문제는 제가 할 때입니다.this.$store.commit('listing',1);이것.this.$store.subscribe((mutation) => {다른 파일에서 이벤트를 두 번 듣기 때문에 예상되는 동작인 twice twice 트리거, 구성 요소당 한 번만 트리거할 수 있는 방법이 있습니까?

돌연변이 청취자를 부르는 이유는home.vue그 이유는 해당 구성 요소에 대해서만 특별히 실행하고 싶은 이벤트가 있기 때문입니다.

당신은 샘플 코드를 듣습니다.listing둘 다를 위한 거스름app.vue그리고.home.vue하지만 당신의 게시물에 따르면, 그들은 다른 종류의 변화에 관심이 있는 것처럼 보입니다.

말씀하신 대로.watch스토어의 모든 변경보다는 몇 가지 변경에만 관심이 있다면 더 나은 접근 방식이 될 것입니다.다음과 같은 것:


// home.vue
new vue({
    el : '#app',
    components : { home_tpl },
    created(){
        this.$store.watch((state, getters) => state.stateHomeIsInterested, (newVal, oldVal) => {
            alert()
        })
    }
})

// app.vue
export default{
    created(){
        this.$store.watch((state, getters) => state.stateAppIsInterested, (newVal, oldVal) => {
            alert()
        })
    }
}

차이점은 다음과 같습니다.

  • subscribe스토어에 변형이 있을 때마다 콜백이 호출됩니다(당신의 경우 불필요한 콜백 호출이 낭비될 수 있습니다).콜백 메서드는 변환 및 업데이트된 상태를 인수로 수신합니다.
  • watch첫 번째 인수에 정의된 getter의 반환 값에 대한 변경 사항에만 반응하며, 콜백은 새 값과 이전 값을 인수로 수신합니다.필요한 경우 여러 상태를 볼 수 있습니다.

언급URL : https://stackoverflow.com/questions/55531088/vuex-mutation-subscription-trigger-multiple-times