【问题标题】:Vue multiplying values in a data tableVue在数据表中相乘
【发布时间】:2021-06-17 06:52:34
【问题描述】:

如何使用 Vue.js 将表中的值相乘? 宏观值是针对 100 克产品给出的。 当我输入 200g 时,我希望数值翻倍,即 318kcal、12 脂肪、48 碳水化合物、8 蛋白质、2% 铁。 当我输入 50g 时:79.6kcal、3 脂肪、12 碳水化合物、2 蛋白质、0.5 铁等。

演示代码 here

HTML:

<div id="app">
  <v-app id="inspire">
    <v-data-table :headers="headers" :items="desserts" :items-per-page="5" class="elevation-1" hide-default-footer>

      <template v-slot:item.quantity="{ item }">
        <v-text-field value="" :placeholder="item.quantity" type="number" suffix="g">
        </v-text-field>
      </template>

    </v-data-table>
  </v-app>
</div>

JS:

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      headers: [
        {
          text: 'Dessert (100g serving)',
          align: 'start',
          sortable: false,
          value: 'name',
        },
        { text: 'Calories', value: 'calories' },
        { text: 'Fat (g)', value: 'fat' },
        { text: 'Carbs (g)', value: 'carbs' },
        { text: 'Protein (g)', value: 'protein' },
        { text: 'Iron (%)', value: 'iron' },
        { text: 'Quantity', value: 'quantity' },
      ],
      desserts: [
        {
          name: 'Frozen Yogurt',
          calories: 159,
          fat: 6.0,
          carbs: 24,
          protein: 4.0,
          iron: '1%',
          quantity: 0,
        },
      ],
    }
  },
  computed: {
    
  }
})

【问题讨论】:

  • 您能否展示您的尝试,以便我们尝试帮助您解决问题?当用户输入内容时,您应该使用计算来为您计算这些值。
  • 我相信在这种情况下过滤器会是更好的方法。处理原始数据以供显示是过滤器的设计目的。 vuejs.org/v2/guide/filters.html ...这是假设您为每个表列编写一个模板。

标签: javascript vue.js vuetify.js


【解决方案1】:

如果dessert[].quantity 表示单个份量的量,您可以将v-text-fieldv-model 绑定到将用于计算乘数的数据属性(例如,名为“userQuantities”) :

<template v-slot:item.quantity="{ item, index }">
  <v-text-field v-model="userQuantities[index]"></v-text-field>
</template>
export default {
  data() {
    return {
      userQuantities: []
    }
  }
}

然后创建一个computed property(例如,命名为“computedDesserts”),它根据乘数计算营养价值,乘数是用户数量与单份份量的比率:

export default {
  computed: {
    computedDesserts() {
      return this.desserts.map((dessert,i) => {
        const qty = this.userQuantities[i] || dessert.quantity
        const multiplier = qty / (dessert.quantity || 1)
        return {
          ...dessert,
          calories: dessert.calories * multiplier,
          fat: dessert.fat * multiplier,
          carbs: dessert.carbs * multiplier,
          protein: dessert.protein * multiplier,
          iron: `${parseInt(dessert.iron) * multiplier}%`,
        }
      })
    }
  }
}

并更新您的模板以使用computedDesserts 而不是desserts

<v-data-table :items="computedDesserts">

updated codepen

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    相关资源
    最近更新 更多