我有一个项目列表,我想对当前选定的项目应用一种样式。我也在使用 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.delete
和 Vue.set
函数。
关于javascript - Vue.js 'v-bind:class' 不更新,即使模型更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41185809/