【问题标题】:Vuex array getters didnt get triggered whenever state changes? Nuxt每当状态更改时,Vuex 数组 getter 都不会被触发?纽斯特
【发布时间】:2020-02-17 23:17:37
【问题描述】:

我的问题是,每当状态发生变化时,getter 都不会发生变化。我猜是因为吸气剂无法检测到数组中的变化?

Vuex 代码

// State - Basic data for the cart
export const state = () => ({
  cart: [{ _id: 1, price: 1000} , {_id: 2, price: 2000 } , { _id: 3, price: 222}],
});

//Mutations - Find the product with same id and change the price
export const mutations = () = ({
    changePrice(state, { id, newPrice }) {
    const cartProduct = state.cart.find(item => item._id === id);
    cartProduct.price = newPrice
    }
})

// Getters - Get all price and combine it so - 1000 + 2000 + 222 = 3222
export const getters = {
 cartTotalPrice(state) {
     return state.cart.reduce((total, product) => {
       return total + product.price;
     }, 0);
  },
}

价格.vue

<template>
   <!-- Basic input with type number and button to do an action -->
   <div>
       <input type="number" v-model="price" />
       <button @click="onChangePrice">
       <h3>{{ cartTotalPrice }}</h3>
  </div>
</template>
<script>
  export default {
     data() {
        return { price: 0 }
     }

     computed: {
        ...mapGetters(['cartTotalPrice'])
     },
     methods: {
       onChangePrice() {
           this.$store.commit('changePrice', {_id: 1, newPrice: this.price });
       }

     }
  }

</script>

关于如何继续获得反应式吸气剂的任何建议,我应该更换数组吗?

【问题讨论】:

  • 在使用状态中的数组和对象时,您需要使用 Vue.set() 或完全替换 Mutation 中的状态对象,否则它不是反应性的。此外,您应该只通过操作调用 Mutation,而不是在您的 UI 中。在该操作中,您实际上会查找产品,然后将状态的新副本作为有效负载传递到突变中。基本上尽量避免突变中的业务逻辑。我什至会说“changePrice”应该是您的 Action,这应该称为更通用的“更新购物车”突变。
  • 你能展示一些我需要一些可视化的例子吗

标签: vue.js vuex nuxt.js


【解决方案1】:

我看到两个错误。

这个:

this.$store.commit('changePrice', {1, this.price });

应该是这样的:

this.$store.commit('changePrice', { id: 1, newPrice: this.price });

第二个问题是mutations的定义:

export const mutations = (state, { id, newPrice }) = ({
    changePrice() {

我真的不知道那里发生了什么,但我假设你的意思是这样的:

export const mutations = {
    changePrice(state, { id, newPrice }) {

【讨论】:

  • 感谢您的回答!不幸的是,它仍然是一样的。我已更改以匹配您的代码,但仍然无法正常工作。再次感谢
  • @airsoftFreak 问题中的更新代码包含export const mutations = () = ({,这是无效的JavaScript。我建议您在changePrice 中输入一些控制台日志,以检查它是否被正确调用,并使用 Vue 开发工具检查 state 商店是否正在更新。您现在已经发布了几次无效的 JavaScript 语法,这让我想知道您是否以某种方式隐藏了错误消息。
猜你喜欢
  • 2020-04-06
  • 1970-01-01
  • 2016-06-05
  • 2021-01-10
  • 2012-02-03
  • 2020-05-07
  • 2019-08-06
  • 2019-10-09
  • 1970-01-01
相关资源
最近更新 更多