所以我有一个简单的商店:
const state = {
cart: []
};
以下是购物车有物品时的样子:
[
{
id: 1,
name: 'My first product',
price: 3,
quantity: 3
},
{
id: 2,
name: 'My second product',
price: 2,
quantity: 7
}
]
这是我对这个对象的突变:
ADDPRODUCTTOCART (state,product,quantity) {
for(var i = 0; i < state.cart.length; i++) {
if(state.cart[i].id === product.id) {
state.cart[i].quantity += quantity;
return ;
}
}
product.quantity = quantity;
state.cart.push(product);
}
如您所见,在将 a 添加product
到 时cart
,我首先检查购物车中是否已经存在相同的产品。如果是,我们更改quantity
值。如果不是,我设置产品对象的数量属性,然后将其推送到购物车。
供您参考,以下是触发此突变的操作的编写方式:
export const addProductToCart = ({dispatch}, product, quantity) => {
dispatch('ADDPRODUCTTOCART', product, quantity);
};
然后,我有一个组件:
export default {
computed: {
total() {
var total = 0;
for(var i = 0; i < this.cart.length; i++) {
total += this.cart[i].price * this.cart[i].quantity;
}
return total;
}
},
vuex: {
getters: {
cart: function (state) {
return state.cart;
}
}
}
}
计算属性total
运行良好,当我更改.product
cart
但是,如果我尝试quantity
在列表中显示此属性v-for
,它不会在更改时更新quantity
:
<li v-for="product in cart" track-by="id">
productID: {{ product.id }},
quantity: {{ product.quantity }}
</li>