Vuex getter没有更新

dan*_*mix 38 vue.js vuex

我有下面的吸气剂:

withEarmarks: state => {
    var count = 0;
    for (let l of state.laptops) {
        if (l.earmarks.length > 0) {
            count++;
        }
    }
  return count;
}
Run Code Online (Sandbox Code Playgroud)

在一个组件中,这个计算属性派生自该getter:

    withEarmarks() { return this.$store.getters.withEarmarks; },
Run Code Online (Sandbox Code Playgroud)

返回的值是正确的,直到我更改laptops数组中的元素,然后getter不会更新.

jps*_*der 80

在你的情况下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)
Run Code Online (Sandbox Code Playgroud)

虽然记录在案,但我想在那个页面上写着一个巨大的霓虹灯发光标志,上面写着"如果你不知道这个,你会浪费数小时的生产力",这将是一个很好的补充.

你可以在这里阅读更多关于这个"警告"的信息:https://vuejs.org/v2/guide/list.html#Caveats

  • `state.laptops = [laptop,... state.laptops]` (3认同)
  • 实际上是这个的忠实粉丝.`[laptop,... state.laptops]`基本上是一个`unshift`和[... state.laptops,笔记本电脑]是`push`. (2认同)
  • 这是此问题的不错摘要:>如果您不了解,则会浪费数小时的生产力。” (2认同)
  • “巨大的霓虹灯发光标志”哈哈,太真实了。谢谢如此的存在。 (2认同)