2016-12-27 57 views
1

我有一个功能可以将商品添加到购物车,当商品已经在购物车中时,我预计它只会将该商品的数量加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> 

回答

2

我相信这是因为在VUE变化检测的caveats发生。

由于在JavaScript的限制,Vue的不能检测进行以下更改的数组:

  1. 当直接设置的项与索引,例如vm.items[indexOfItem] = newValue

  2. 当您修改数组的长度时,例如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); 
     } 
}, 
+0

告诉我:“this.set”不是函数 –

+0

在else块中,我正在推送哪些项目?它不应该成为索引吗?我有点困惑。 –

+1

@BernardParah这将是'this。$ set',或者你也可以做'this.cart.splice(index,1,this.cart [index])' – Saurabh