javascript - 单击时显示更新值

标签 javascript vue.js vuejs2

我有一个将商品添加到购物车的功能,当商品已经在购物车中时,我希望它只会将该商品的数量加 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 无法检测到数组的以下更改:

  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);
       }
},

关于javascript - 单击时显示更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41340047/

相关文章:

javascript - NuxtJS 无法使用变量加载多个 CSS 表

vuejs2 - VueJS - 构建后 dist 中的多个 js 文件

javascript - Vue devtool如何检测网页上的Vue?

javascript - Typescript/Vue - 当我为 Prop 声明默认对象时,如何访问 vuex 存储?

javascript - Vue2 传递任意命名变量作为 prop

javascript - 使用 Javascript 定位

javascript - D3.js 微不足道的工具提示

javascript - 如何让 jQuery .change() 引用 Handsontable 上的单元格?

php - 从 View 调用 Controller 方法

vue.js - 具有 v-once 效果的功能组件