【发布时间】:2021-10-04 13:32:46
【问题描述】:
目前,我使用 Vuex 在 Vue 中制作了一个简单的购物车。我遇到的问题是我正在更新购物车对象中产品的数量,但这不会在前端视图上更新(它不是反应式的)。
我目前所做的是更新 cart 数组中的一个对象值,为了让它工作,我需要将现有的购物车设置为一个空数组,然后我重新应用具有新值的旧购物车状态。
更新数组中对象值的最佳方法是什么?
以下是我的模块(vuex)中的以下相关数据:
namespaced: true,
state: {
cart: [],
products: [
{
id: 2,
name: 'Product sweater 2',
},
{
id: 1,
name: 'Product sweater',
}
]
},
mutations: {
update(state, product) {
const index = state.cart.findIndex(x => x.id === product.id)
if (index !== -1) {
state.cart[index].quantity++
state.cart = [
...state.cart
]
} else {
product.quantity = 1
state.cart.push(product)
}
},
}
【问题讨论】: