You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js中如何在v-for内动态添加输入框并绑定数据?

Vue动态新增输入字段的可行解决方案

问题根源

  1. 数组索引从0开始,但原代码用v-for="n in num"遍历的是从1开始的整数,导致itemPrices[n]访问的是数组中不存在的索引(初始数组为空,没有对应位置的对象)。
  2. 直接给数组索引赋值对象时,Vue无法自动检测到数组元素的新增,双向绑定会失效。

修正方案

放弃用num变量控制行数,直接遍历itemPrices数组,通过数组的变异方法(如push)新增元素,确保Vue能追踪到数据变化。

1. 调整data定义

移除多余的num变量,保留初始空数组:

data() {
  return {
    itemPrices: []
  }
}

2. 添加行的方法

点击按钮时,往itemPrices数组中push包含初始值的空对象:

methods: {
  addRow() {
    this.itemPrices.push({ regionId: '', price: '' })
  }
}

3. 修改表格渲染代码

直接遍历数组元素,绑定到对象的属性上:

<vs-tr v-for="(item, index) in itemPrices" :key="index">
  <vs-td>
    <vs-input
      v-model="item.regionId"
      placeholder="Region Name"
    />
  </vs-td>
  <vs-td>
    <vs-input
      placeholder="price"
      v-model="item.price"
    />
  </vs-td>
  <!-- 可选:添加删除行按钮 -->
  <vs-td>
    <button @click="deleteRow(index)">删除</button>
  </vs-td>
</vs-tr>

4. 可选:删除行方法

如果需要支持删除行,添加对应的方法:

deleteRow(index) {
  this.itemPrices.splice(index, 1)
}

为什么这样有效

  • 直接遍历数组元素,v-model绑定到对象的已有属性,Vue能正常追踪双向绑定的变化。
  • 使用Vue能检测到的数组变异方法(push、splice)操作数组,DOM会自动更新。
  • 逻辑更简洁,数组长度直接对应表格行数,无需额外维护num变量。

内容的提问来源于stack exchange,提问作者Arnab Maiti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 13:05:26