javascript - 无法增加/减少Vue中的数据属性值

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

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

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
  }
}

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

最佳答案

将整个产品传递给方法:

<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}}

关于javascript - 无法增加/减少Vue中的数据属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61287124/

相关文章:

javascript - Raphael JS PieChart 选择部分

javascript - 无法在 Vue.js + webpack 中动态传递 imgs 的相对 src 路径

vue.js - 在子项 vueJS.2 之间切换 "active"类

javascript - 关于如何为我的网络应用程序使用 Google 登录的清晰示例/文档

javascript - Rollup + React 17 与新的 JSX 转换 - "React is not defined"

javascript - C# 相当于桌面应用程序的 Android WebView

javascript - vue动态查询key

vue.js - 为什么在vuejs应用程序中vuejs应用程序中的prefer-const规则没有被禁用?

javascript - 重定向同一组件时不会调用 Vuejs 钩子(Hook)

vue2JS 中的服务 - 创建钩子(Hook)时出错