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

Vue中v-for与v-model绑定导致输入行值联动的问题解决

Vue循环输入框值同步问题解决

问题根源

你当前用Array(10).fill({ numInput: '', num2Input: '' })初始化数组时,fill方法会把同一个对象的引用复制到数组的每一项中。也就是说,数组里10个元素实际指向的是同一个对象,所以修改任意一个输入框的v-model,都会同步修改这个唯一对象的属性,导致所有输入框内容同步变化。

解决方法

需要为数组的每一项创建独立的对象实例,避免共享引用。可以用Array.from或map方法实现:

修改后的代码

<template>
  <div class="cont" v-for="(row, index) in 10" :key="index">
    <div class="row">
      <input type="text" v-model="rows[index].numInput" />
    </div>
    <div class="row">
      <input type="text" v-model="rows[index].num2Input" />
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 用Array.from生成10个独立对象
      rows: Array.from({ length: 10 }, () => ({
        numInput: '',
        num2Input: '',
      }))
    }
  },
}
</script>

另一种实现方式(用map)

如果习惯用Array(10),可以结合map生成独立对象:

rows: Array(10).fill(null).map(() => ({
  numInput: '',
  num2Input: '',
}))

原理说明

Array.from的第二个参数是映射函数,每迭代一次就返回一个新的对象字面量,这样数组中每个元素都是独立的引用。此时每个输入框的v-model绑定的是不同对象的属性,修改某一项时不会影响其他项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 01:36:10