IT이야기

Vue.js 'v-bind:class'가 업데이트되지만 업데이트되지 않음

cyworld 2022. 6. 17. 21:48
반응형

Vue.js 'v-bind:class'가 업데이트되지만 업데이트되지 않음

아이템 리스트가 있는데, 현재 선택한 아이템에 스타일을 적용하고 싶습니다.또한 Vuex를 사용하여 상태를 관리하고 있습니다.

내 목록 구성 요소:

const List = Vue.component('list', {
    template:
            '<template v-if="items.length > 0">' +
                '<ul class="list-group md-col-12">' +
                    '<a href="#" v-for="(item, index) in items" class="list-group-item list-group-item-action" v-bind:class="{ active: item.isActive }" v-on:click="selectItem(index);">{{ g.text }}</a>' +
                '</ul>' +
            '</template>'
    computed: {
        items: function() {
            return this.$store.state.items;
        }
    },
    methods: {
        selectItem: function (index) {
            this.$store.commit('selectItem', index);
        }
    }
});

내 가게:

const store = new Vuex.Store({
    state: {
        items: [],
        currentIndex: -1
    },
    mutations: {
        selectItem: function(state, index) {
            if (index === state.currentIndex) {
                return;
            }
            if (state.currentIndex > -1) {
                delete state.items[state.currentIndex].isActive;
            }
            state.currentIndex = index;
            state.items[state.currentIndex].isActive = true;
        }
    }
});

Chrome DevTools의 Vue '탭'을 사용하면 목록의 항목을 클릭할 때마다 "항목" 배열이 올바르게 업데이트되지만 클래스가 설정되지 않습니다.

또한 시간 이동 디버깅을 사용하여 모든 돌연변이를 조사하면 클래스가 설정됩니다.

왜 이런 행동을 하는지, 어떻게 고칠 수 있는지 아세요?

그 문서를 좀 더 자세히 읽었어야 했어요.특히 변경검출에 관한 경고.

해결책은 다음과 같이 스토어 돌연변이를 변경하는 것이었습니다.

selectItem: function(state, index) {
    if (index === state.currentIndex) {
        return;
    }
    if (state.currentIndex > -1) {
        Vue.delete(state.items[state.currentIndex], 'isActive');
    }
    state.currentIndex = index;
    Vue.set(state.items[state.currentIndex], 'isActive', true);
}

여기서 중요한 것은Vue.delete그리고.Vue.set기능들.

기타 답변은 https://stackoverflow.com/a/40961247/525843에 도움이 되었습니다.

다음을 수행해 보십시오.

const List = Vue.component('list', {
    template:
            '<template>' +
                '<ul class="list-group md-col-12">' +
                    '<a href="#" v-for="(item, index) in items" class="list-group-item list-group-item-action" v-bind:class="{ active: item.isActive }" v-on:click="selectItem(index);">{{ g.text }}</a>' +
                '</ul>' +
            '</template>'

언급URL : https://stackoverflow.com/questions/41185809/vue-js-v-bindclass-doesnt-update-even-though-model-does

반응형