【问题标题】:Update input field total from variable number of input fields in Vue2从 Vue2 中可变数量的输入字段更新输入字段总数
【发布时间】:2021-07-30 18:28:09
【问题描述】:

我有可变数量的输入字段,用于从以数字作为输入的 API 响应生成的产品数量输入。一旦用户更改输入字段值,我需要更新每个项目的总价和所有项目的小计。

这是我正在尝试的 数据:

 "productList": [
                {
                    "id": 27,
                    "product_id": "2362",
                    "product_name": "nengra",
                    "unit": "box",
                    "minimum_order": "1",
                    "unit_price": "890",
                    "photo_url": "http://45.114.85.21:11011/micro_product/mv8gigsx2e_7a4i2twgv6.jpg"
                },
                {
                    "id": 29,
                    "product_id": "2365",
                    "product_name": "nengra",
                    "unit": "box",
                    "minimum_order": "1",
                    "unit_price": "890",
                    "photo_url": "http://45.114.85.21:11011/micro_product/qdmiugpabf_4ojvtkryym.jpg"
                }
    ]

模板:

<div v-for="{{products in productList}}" :key="products.product_id">
    <input type="number" v-model="products.qty" v-on:change="updateCart" >
<p>{{products.productsTotal}}</p>
</div>
    <p>{{subTotal}}</p>

脚本:

 data(){
    return{
      qty:[],
      cartID: null,
      productList: [],
      total: 0,
      subtotal: 0,
      productTotal: 0
    }
  },
  methods: {
    updateCart: function (){
        this.products.productTotal = this.products.qty * this.productList.price
    }
  }

我是 Vue2 的新手,请帮我整理一下。谢谢

【问题讨论】:

  • this.productsundefinedsubTotal 未定义。请创建一个minimal reproducible example 之类的代码框并尝试运行代码,您将在控制台中看到错误。

标签: vue.js vuejs2


【解决方案1】:

您可以为subTotal 使用这样的计算属性:

computed: {
    subTotal: function () {
      return this.productList.reduce(
        (p, np) => p.productTotal + np.productTotal
      );
    },
  },

v-on:change="updateCart(product)" 之类的引用传递给点击的产品以更新其值:

methods: {
    updateCart: function (product) {
      product.productTotal = Number(product.qty) * Number(product.unit_price);
    },
 },

每次我们在这里更新product.productTotal 时,subTotal 都会自动更新,因为它是一个计算属性。

旁注:我为每个产品添加了productTotal 属性。如果您的数据不包含它,您可以在设置数据之前在API成功回调中手动添加。

【讨论】:

    猜你喜欢
    • 2013-06-11
    • 1970-01-01
    • 2011-09-13
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    相关资源
    最近更新 更多