【问题标题】:Sum two items in table row将表格行中的两项相加
【发布时间】:2019-09-13 00:11:40
【问题描述】:

我正在使用 Vue 整理一个简单的报价页面,我试图将同一行中的两个项目相加。我尝试使用计算属性,但我在格式上苦苦挣扎。根据我的示例,我应该如何格式化以显示每行的支出和价格总和?

new Vue({
  el: '#search',
  data: {
    items: [
      { province: "Alberta", disbursement: 1, price: 300 },
      { province: "British Columbia", disbursement: 1, price: 75 },
      { province: "Manitoba", disbursement: 1, price: 10 },
      { province: "New Brunswick", disbursement: 1, price: 10 },
      { province: "Newfoundland & Labrador", disbursement: 1, price: 10 },
      { province: "Nova Scotia", disbursement: 1, price: 10 },
      { province: "Northwest Territories", disbursement: 1, price: 10 },
      { province: "Nunavut", disbursement: 1, price: 10 },
      { province: "Ontario", disbursement: 1, price: 10 },
      { province: "Prince Edward Island", disbursement: 1, price: 10 },
      { province: "Quebec", disbursement: 1, price: 10 },
      { province: "Saskatchewan", disbursement: 1, price: 10 },
      { province: "Yukon", disbursement: 1, price: 10 },
    ]
  },

computed: {
    total: function() {
    return parseInt(this.items.disbursement) +
        parseInt(this.items.price);
}
}

});

我的 HTML 格式是这样的

<tr v-for="item in items">
    <th scope="row"><input type="text" v-model="item.province"/></th>
    <td>$<input type="number" v-model="item.price"/></td>
    <td>$<input type="number" v-model="item.disbursement"/></td>    
    <td>${{total}}</td>
</tr>

我正在尝试在总数中添加 items.disbursement + items.price

【问题讨论】:

标签: vue.js


【解决方案1】:

听起来您需要迭代“项目”并对每个“项目”的属性求和。

以下代码将返回一个整数数组,但您可以根据需要设置数组值的格式,只需编辑 map 函数返回的内容。

computed: {
    total: function() {
      return this.items.map(i => {
        return parseInt(i.disbursement) + parseInt(i.price)
      }
}

【讨论】:

    猜你喜欢
    • 2017-06-12
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多