【问题标题】:Vuex getter not updating on state changesVuex getter 不更新状态变化
【发布时间】:2019-08-06 09:51:51
【问题描述】:

当状态对象发生变化时,我无法更新 vuex getter。 我试图让一个 vuex getter 使用 reduce 函数返回状态对象中值的总和。

// Mutation
state.shippingFees[method.sellerId] = method.fee; // state.shippingFees = { 1: 1900 }; etc.

// Getter
totalShippingFees: state => Object.values(state.shippingFees).reduce((total, fee) => total + fee, 0)

在 state.shippingFees 对象中设置运费键值对后,getter 仍然只是返回 0。

【问题讨论】:

  • 变异应该是函数调用,这里只是更新不允许的状态

标签: javascript vue.js vuejs2 vuex


【解决方案1】:

Vue 不允许将新的根级反应属性动态添加到已创建的实例中。但是,可以使用 Vue.set(object, key, value) 方法向嵌套对象添加响应式属性

因此,您更新上述对象的方式不是反应性的。因此,您的值不会在 getter 中更新。要了解有关 vue 反应性的更多信息,请阅读 here

要使其具有响应性,您需要使用 $set 或 object.assign

如下更新你的变异 =>

Vue.$set(state.shippingFees,method.sellerId,method.fee);

【讨论】:

    【解决方案2】:

    Vue 无法检测到属性添加或删除

    使用Vue.set(state.shippingFees, method.sellerId, method.fee)

    更多详情here

    【讨论】:

      【解决方案3】:

      参考Vue官方文档Caveats。您不能按索引更改数组元素。有一些方法可以通过下面给出的反应性来实现相同的目标

      state.shippingFees.splice(index, 1, val) 
      //using the splice method, replace the element at index
      

      或者。或者,您可以使用

      Vue.set(state.shippingFees, index , val)
      
      //You can also use the vm.$set instance method, which is an alias for the global Vue.set method
      vm.$set(vm.items, indexOfItem, newValue)
      

      当你直接使用索引更新item,或者修改数组长度属性时,Vue无法检测到变化。

      【讨论】:

        猜你喜欢
        • 2020-05-07
        • 2021-06-19
        • 2017-12-08
        • 2019-11-30
        • 1970-01-01
        • 2020-12-18
        • 2017-12-24
        • 2020-11-23
        • 2020-12-22
        相关资源
        最近更新 更多