所以我有一个简单的商店:
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);
}
如您所见,将产品
添加到购物车
时,我首先检查购物车中是否已存在相同的产品。如果是,我们更改 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>
最佳答案
如果你想从组件的data
传递数据,你应该移除观察者:
JSON.parse(JSON.stringify(this.products[0]))
关于javascript - 列表渲染中的 Vuex 和 react 性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37818570/