vue:v-model 绑定 v-for 循环别名报错问题

在 Vue 中,直接将 v-model 绑定到 v-for 的迭代别名会导致报错,因为修改迭代别名相当于修改函数的局部变量,无法更新源数组。

示例:错误代码

<div v-for="(item, index) in data" :key="index">
 <input v-model="item" /> <!-- 报错 -->
</div>

报错信息: You are binding v-model directly to a v-for iteration alias. This will not be able to modify the v-for source array...

正确解决方法

使用索引绑定源数组

通过索引直接引用源数组中的元素,确保修改的是数组本身。

修改为:

<div v-for="(item, index) in data" :key="index">
 <input v-model="data[index]" />
</div>

或修改源数据使用对象数组并绑定对象属性

如果数据是对象数组,可以直接绑定对象的属性。

示例:

data: [
 { value: 'Item 1' },
 { value: 'Item 2' },
]

<div v-for="(item, index) in data" :key="index">
 <input v-model="item.value" />
</div>

通过以上方法,可以避免直接绑定迭代别名的问题,并确保数据的响应式更新。

posted @ 2025-11-20 15:40  大萨特  阅读(5)  评论(0)    收藏  举报