【问题标题】:Vue.js 'v-bind:class' doesn't update even though model does即使模型更新,Vue.js 'v-bind:class' 也不会更新
【发布时间】:2016-12-16 13:44:46
【问题描述】:

我有一个项目列表,我想为当前选定的项目应用一种样式。我也在使用 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 的“选项卡”时,每当我点击列表中的一个项目时,“项目”数组都会正确更新,但没有在它们上设置类。

此外,使用时间旅行调试来遍历所有突变,在这种情况下,类已设置。

知道为什么会出现这种行为以及如何解决它吗?

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    事实证明,我应该更深入地阅读文档。特别是Change Detection Caveats

    解决方案是这样更改存储突变:

    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.deleteVue.set 函数。

    其他对我有帮助的答案https://stackoverflow.com/a/40961247/525843

    【讨论】:

    • 这里有点晚了,但它可能会帮助其他人,所以:你也可以这样使用set对象:this.arrayWithObjects1.forEach((item) =&gt; { this.$set(this.arrayWithObjects2, item.propertyName, 'newValue'); });
    【解决方案2】:

    尝试以下操作:

    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>'
    

    【讨论】:

    • 我明天试试,谢谢。同时,您能否提供更多背景信息?我看到的与我的模板的唯一区别是您删除了模板元素上的“v-if”。为什么会有不同?
    • 我试过了,因为我认为它没有区别
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    • 2018-04-07
    • 2016-06-15
    • 2019-04-22
    • 1970-01-01
    • 2015-07-30
    相关资源
    最近更新 更多