Vuex getter 没有更新
Vuex getter not updating
我有以下 getter:
withEarmarks: state => {
var count = 0;
for (let l of state.laptops) {
if (l.earmarks.length > 0) {
count++;
}
}
return count;
}
并且在一个组件中,此计算 属性 派生自 getter:
withEarmarks() { return this.$store.getters.withEarmarks; },
返回的值是正确的,直到我更改了 laptops 数组中的一个元素,然后 getter 没有更新。
在你的例子中 state.laptops.earmarks
是一个数组,你通过它的数组索引 state.laptops[index]
来操作它。 Vue 无法对状态数组(按索引)上的突变做出反应。文档为此提供了 2 个解决方法:
// 1. use purpose built vue method:
Vue.set(state.laptops, index, laptop)
// 2. splice the value in at an index:
state.laptops.splice(index, 1, laptop)
尽管已记录在案,但我认为该页面上的一个巨大的霓虹灯标志写着“如果您不知道这一点,您将浪费数小时的工作效率”将是一个不错的补充.
您可以在此处阅读有关此“警告”的更多信息:https://vuejs.org/v2/guide/list.html#Caveats
除了 Reactivity 问题和 Vue 警告之外,可能还有另一个原因,您在计算函数中引入了局部变量 counter
,您可以尝试使用给定的 reduce
函数。
withEarmarks: state => {
return state.laptops.reduce((acc, item) => {
if(item.earmarks.length > 0){
acc++;
}
return acc;
}, 0);
}
考虑@jpschroeder 的回答以及这个答案。
我有以下 getter:
withEarmarks: state => {
var count = 0;
for (let l of state.laptops) {
if (l.earmarks.length > 0) {
count++;
}
}
return count;
}
并且在一个组件中,此计算 属性 派生自 getter:
withEarmarks() { return this.$store.getters.withEarmarks; },
返回的值是正确的,直到我更改了 laptops 数组中的一个元素,然后 getter 没有更新。
在你的例子中 state.laptops.earmarks
是一个数组,你通过它的数组索引 state.laptops[index]
来操作它。 Vue 无法对状态数组(按索引)上的突变做出反应。文档为此提供了 2 个解决方法:
// 1. use purpose built vue method:
Vue.set(state.laptops, index, laptop)
// 2. splice the value in at an index:
state.laptops.splice(index, 1, laptop)
尽管已记录在案,但我认为该页面上的一个巨大的霓虹灯标志写着“如果您不知道这一点,您将浪费数小时的工作效率”将是一个不错的补充.
您可以在此处阅读有关此“警告”的更多信息:https://vuejs.org/v2/guide/list.html#Caveats
除了 Reactivity 问题和 Vue 警告之外,可能还有另一个原因,您在计算函数中引入了局部变量 counter
,您可以尝试使用给定的 reduce
函数。
withEarmarks: state => {
return state.laptops.reduce((acc, item) => {
if(item.earmarks.length > 0){
acc++;
}
return acc;
}, 0);
}
考虑@jpschroeder 的回答以及这个答案。