javascript - 在 vue.js 中计算小计

标签 javascript html vue.js

我有一个 vue js 项目,它就像一个购物车。 我想计算每行产品的小计。

我的html代码:

<div id="app">
<table border="1">
    <thead>
    <tr>
        <th>#</th>
        <th>title</th>
        <th>price</th>
        <th>quantity</th>
        <th>subtotal</th>
    </tr>
    </thead>
    <tbody>
    <tr v-for="product in products" :key="product.id">
        <td>{{ product.id }}</td>
        <td>{{ product.title }}</td>
        <td>{{ product.price }}</td>
        <td><input type="number" v-model="product.quantity"></td>
        <td>{{ product.subtotal }}</td>
    </tr>
    </tbody>
</table>
</div>

我的js代码是:

var app = new Vue({
    el: '#app',
    data: {
        products: [
            {
                "id": 1,
                "title": "first",
                "price": 151,
                "quantity": 0,
                "subtotal": 0
            },
            {
                "id": 2,
                "title": "second",
                "price": 152,
                "quantity": 0,
                "subtotal": 0
            },
            {
                "id": 3,
                "title": "another record",
                "price": 0,
                "quantity": 0,
                "subtotal": 0
            },
            {
                "id": 4,
                "title": "hello",
                "price": 0,
                "quantity": 0,
                "subtotal": 0
            },
            {
                "id": 5,
                "title": "world",
                "price": 0,
                "quantity": 0,
                "subtotal": 0
            }
        ]
    },
    computed:{
        'product.subtotal': function(){
            return product.quantity * product.price;
        }
    }
});

如何通过更改数量来计算任何产品的小计? 我想将计算出的小计保存到product.subtotal 属性中。

这是 jsfiddle 链接: https://jsfiddle.net/s38wLk49/

最佳答案

错误(嗯,不完整): 将 {{product.subtotal }} 更改为 {{product.price * Product.quantity }} 不会吗?

由于他想要实际更改数据,而不仅仅是显示,这就是我尝试过的并且它对我有用:

watch:{
  products:{
   handler:function(newval,oldval) {
      this.products.forEach(p => {
          p.subtotal = p.price * p.quantity;
      });
   }, deep:true
  }
}

Vue 支持监视对象的属性,但据我所知,它不适用于对象的数组(我可能是错的!)。

关于javascript - 在 vue.js 中计算小计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49259045/

相关文章:

html - 在移动设备上缩小网页会导致行偏移

vue.js - 如何在 ChartJS 中的数据上放置符号 (%)?

c# - 如何显示图片裁剪区域

javascript - Cypress 拦截 - 在同一测试用例中使用不同的有效载荷多次执行相同的 api

javascript - 使用 CSS 逐渐改变图像(删除过渡)

javascript - JQuery 问题 : Sticky menu shifts to the right when it sticks

javascript - Angular 谷歌地图信息窗口图标不可点击

javascript - 如何将对话框的创建移动到 jQuery UI 中的外部函数中?

javascript - 如何将vuejs for循环索引值作为HTML按钮onclick javascript函数的参数传递

尝试在 aws ec2 ubuntu 上运行 npm run dev 时,Laravel Vue 卡住了