Ste*_*han 6 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);
}
}
});
Run Code Online (Sandbox Code Playgroud)
我的商店:
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;
}
}
});
Run Code Online (Sandbox Code Playgroud)
我所看到的,同样使用Chrome DevTools中的Vue'标签'是每当我点击列表中的项目时,"items"数组正在被正确更新,但是没有在它们上设置类.
此外,使用时间旅行调试来完成所有突变,在这种情况下,类被设置.
知道为什么这种行为以及如何解决它?
Ste*_*han 11
事实证明我应该更深入地阅读文档.特别是变化检测警告.
解决方案是改变商店突变:
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);
}
Run Code Online (Sandbox Code Playgroud)
这里的关键是使用Vue.delete和Vue.set函数.
其他答案帮助了我/sf/answers/2867287321/