为什么 v-model 不适用于数组和 v-for 循环? [英] Why v-model doesn't work with an array and v-for loop?

查看:71
本文介绍了为什么 v-model 不适用于数组和 v-for 循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的选择组件,它使用一个简单的变量,但是当与 v-for 一起使用时它不起作用:

I got a custom select component, it works with a simple variable, but when used with v-for it won't work:

https://jsfiddle.net/7gjkbhy3/19/

<select2 v-for="item, index in samples" v-model="item" ></select2>
data : { samples : [0, 0, 0]}

这有效:

<select2 v-model="sample"></select2>
data : { sample : 0}  

我在这里遗漏了什么?

推荐答案

v-modelv-for 如果 v-model 不能很好地配合 用于带有原始值的迭代别名.

v-model and v-for do NOT go together well if v-model is used to an iteration alias w/ a primitive value.

Vue 警告:

您将 v-model 直接绑定到 v-for 迭代别名.这会无法修改 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. Consider using an array of objects and use v-model on an object property instead.

因此,使用一个对象数组,每个对象都有一个选择值的属性可以解决这个问题:

Therefore using an array of objects each of which has a property for the select value would solve the issue:

工作示例.

<select2 v-for="item, index in samples" v-model="item.value" ></select2>

new Vue({
     el: '#app',
     data: {
         sample: 0,
         samples : [{ value: 0 }, { value: 0 }, { value: 0 }]
     }
 })

这篇关于为什么 v-model 不适用于数组和 v-for 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆