【发布时间】:2016-10-15 13:45:15
【问题描述】:
所以我有一个简单的商店:
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);
}
如您所见,在将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 计算属性运行良好,当我更改cart 中product 对象的数量时,它会自行更新。
但如果我尝试在 v-for 列表中显示此 quantity 属性,当 quantity 更改时它不会更新:
<li v-for="product in cart" track-by="id">
productID: {{ product.id }},
quantity: {{ product.quantity }}
</li>
【问题讨论】:
-
我用你的代码创建了一个小提琴,它可以工作:jsfiddle.net/pespantelis/Lgnvno7h
-
您好,感谢您的回复,我为我的问题编辑了您的小提琴:jsfiddle.net/Lgnvno7h/2 当我尝试发送包含在 Vue 数据中的对象时,它不再起作用了。
标签: javascript vue.js vuex