我有一个将商品添加到购物车的功能,当商品已经在购物车中时,我希望它只会将该商品的数量加 1(确实如此)。
问题是我无法查看更新的数量,直到有另一个操作,例如将另一个项目添加到购物车。
我遵循了 similar question 中的解决方案但对我仍然不起作用。
我希望能够在添加项目后立即查看更新后的值。
addItemToCart : function(item){
if(this.cart.includes(item)){
item.quantity += 1;
console.log(item.quantity);
}
else{
this.cart.push(item);
this.set(item.quantity = 1);
}
},
HTML:
<ul>
<li>Cart is empty</li>
<li v-for="item in cart">
{{item.name }}
<span class="pull-right">
({{ item.price }} x {{ item.quantity }})
<i class="glyphicon glyphicon-remove cart-item-action" @click="removeItemFromCart(item)"></i>
</span>
</li>
</ul>
最佳答案
我相信这是因为 caveats 而发生的vue 中的变化检测。
由于 JavaScript 的限制,Vue 无法检测到数组的以下更改:
当您直接使用索引设置项目时,例如
vm.items[indexOfItem] = newValue
当您修改数组的长度时,例如
vm.items.length = newLength
所以您需要做的是,您可以在函数 addItemToCart
中传递该购物车项目的索引并使用 Vue.set
,如下所示:
addItemToCart : function(item){
if(this.cart.includes(item)){
var index = this.cart.indexOf(item)
this.cart[index] += 1
Vue.set(this.cart, index, this.cart[index])
//or
// this.$set(this.cart, index, this.cart[index])
//or
// this.cart.splice(index, 1, this.cart[index])
console.log(item.quantity);
}
else{
this.cart.push(item);
this.set(item.quantity = 1);
}
},
关于javascript - 单击时显示更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41340047/