需要合作伙伴联系我,VX(绿泡泡): w6668263      email:ye583025823@126.com

v-for 循环时直接使用 v-model 绑定报错

报错信息:You are binding v-model directly to a v-for iteration alias. This will not be able to modify the v-for source array because writing to the alias is like modifying a function local variable.

 

错误代码

<div v-for="(item, index) in data" :key="index">
    // 直接绑定 v-for循环的item成员会报错
    <input v-model="item" />
</div>

将 v-model 直接绑定到 v-for 迭代别名。这将无法修改 v-for 源数组,因为写入别名就像修改函数局部变量一样。考虑使用一个对象数组并在对象属性上使用 v-model。
原因:v-model 不可以直接修改 v-for 循环迭代时别名上的数据,但是,可以通过 index 下标来引用所需的数据,可以达到相同目的。

 

 

正确代码

<div v-for="(item, index) in data" :key="index">
    // 通过index, 绑定数组中对应项
    <input v-model="data[index]" />
</div>

 总结:

如果你绑定的变量名本来不是对象的属性时,需要将变成对象的属性名

原理比较简单,就是在JS中对象,获取属性值时使用的方法不同造成的结果,如果是使用对象.属性名的方式来获取的话,属性名是不能为变量的;但是使用对象[属性名]这种方式时,属性名就可以为变量。

posted on 2024-04-25 23:41  龙行龘龘9527  阅读(436)  评论(0编辑  收藏  举报

导航