javascript - Vue.js 'v-bind:class' 不更新,即使模型更新

标签 javascript vue.js vuejs2

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

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

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

最佳答案

事实证明我应该更深入地阅读文档。特别是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

关于javascript - Vue.js 'v-bind:class' 不更新,即使模型更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41185809/

相关文章:

javascript - 单击时激活 v-for 循环内的项目

javascript - 当选择文件时,Jquery 显示一个或多个文件名

javascript - 如何在WordPress内容(single.php)中添加自动折叠/展开?

javascript - 当用户移动元素时,如何使用 jQuery sortable 更新 div ID?

vue.js - 如何检查vue-router中是否存在命名 View

javascript - ES6 语法在 WebStorm 的 .vue 文件中突出显示为错误。我怎样才能解决这个问题?

javascript - React Material UI CardHeader 标题溢出点

javascript - this.$refs[ ("p"+ index)].focus 不是函数

javascript - 使用浏览器后退按钮 vue.js 的状态历史记录

javascript - Snackbar Vuetify - 超时后覆盖方法