【问题标题】:Can't increase / decrease data property value in Vue无法在 Vue 中增加/减少数据属性值
【发布时间】:2020-07-31 20:52:20
【问题描述】:

我是 Vue.js 的新手,在 Vue 反应性方面面临一个简单的问题。我正在尝试增加或减少数据属性中的值,并实时更新另一个相关值。这是我的代码演示:

https://codesandbox.io/s/crimson-http-srkz0?file=/src/App.vue

<div v-for="(product,index) in products" :key="index" style="padding-top:10px">
   <button @click="decrement(product.quantity)">-</button> 
   {{product.quantity}}
   <button @click="increment(product.quantity)">+</button>
   {{product.title}} 
   costs ${{calculateSubtotal(product.price,product.quantity)}}
</div>
data(){
  return{
    products:[
      {
       title:'ball',
       quantity: 2,
       price: 25
      },
      {
       title:'bat',
       quantity: 1,
       price: 79
      },
    ]
  }
},
methods:{
  increment(n){
    return n+=1;
  },
  decrement(n){
    return n-=1;
  },
  calculateSubtotal(price,quantity){
    return price*quantity
  }
}

预期输出: 这些按钮应该可以增加或减少价值并实时计算成本。有谁能够帮我 ?提前致谢。

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component v-for


    【解决方案1】:

    将整个 product 传递给方法:

    <button @click="decrement(product)">-</button> 
    {{product.quantity}}
    <button @click="increment(product)">+</button>
    {product.title}} 
    

    并像这样修改它们:

    increment(p){
       p.quantity += 1;
    },
    decrement(p){
       p.quantity -= 1;
    },
    

    否则,该方法只会接收值的副本并对其进行修改,而不是对象属性。

    不用这样的方法你也可以做到:

    <button @click="product.quantity--">-</button> 
    {{product.quantity}}
    <button @click="product.quantity++">+</button>
    {{product.title}}
    

    【讨论】:

    • 它有效@Dan。谢谢!您能否回答我另一个问题,即如何从列表中删除项目。这是我的想法codesandbox.io/s/crimson-http-srkz0?file=/src/App.vue
    • 不客气。最简单的删除方法如下:&lt;button @click="products.splice(index, 1)"&gt;Remove&lt;/button&gt;。或者您可以将索引传递给 remove(index) 方法并调用它:this.products.splice(index, 1)
    • 有效!但是我怎样才能在这里使用 Vue.delete @Dan?
    • &lt;button @click="$delete(products, index)"&gt;Remove&lt;/button&gt;。或者您可以将索引传递给 remove(index) 方法并调用它:this.$delete(this.products, index)
    猜你喜欢
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 2019-09-03
    • 2012-05-30
    • 2016-05-05
    • 1970-01-01
    相关资源
    最近更新 更多