Vue Pinia 如何更新对象内的属性

ST8*_*T80 6 javascript vue.js vuejs3 pinia

我正在使用pinia并且我想知道如何更新对象内的属性。我在 中有一个对象数组state.cart,其中是一些产品,它们都有一个名为 的属性quantity。该属性可以更改,因此我需要“更新”购物车数据。

这是我尝试过的:

state: () => ({
   cart: []
}),

actions: {
  updateQuantityOfProduct(product, val) {
    const prod = this.cart.find((item) => item.id === product.id)
    prod.quantity = val
    this.$patch({
      cart: this.cart,
    })
  },
}
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用,因为购物车未更新和/或当我刷新时,尚未添加更新/更改(产品数量与更改前相同)

我该如何解决这个问题以及我做错了什么?

小智 -1

我遇到了和你一样的问题。在发布之前的答案并再次重写后,我解决了我的问题。我不确定为什么你的版本不起作用,也许你可以尝试以下版本。

export const useCartStore = defineStore('carts', {
  state: () => {
    return {
      cart: [],
    }
  },
  actions: {
    updateQuantityOfProduct(product, val) {
      this.cart.map(item => {
        if (item.id === product.id) {
          item.quantity = val
        }
      })
    },
  },
})
Run Code Online (Sandbox Code Playgroud)