Javascript v-for 循环 Vue 2 中的动态 V 模型名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43364487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamic V-model name in a v-for loop Vue 2
提问by Siavosh
I am developing an application and I am using Vue 2as the javascript framework,
inside a v-forloop I need the counter of the loop to be bound to the v-modelname of the elements, this my code:
我正在开发一个应用程序,我将其Vue 2用作 javascript 框架,在v-for循环内我需要将循环的计数器绑定到v-model元素的名称,这是我的代码:
<div v-for="n in total" class="form-group">
<input type="hidden" id="input_id" :name="'input_name_id[' + n + ']'" v-model="form.parent_id_n" />
</div>
I need nto be the counter of the loop, for example for the first element it should be:
我需要n成为循环的计数器,例如对于第一个元素,它应该是:
<div class="form-group">
<input type="hidden" id="input_id" :name="'input_name_id[1]" v-model="form.parent_id_1" />
</div>
the name attributebinding works but I have no idea how to get the v-modelworking as well?
在name attribute结合的作品,但我不知道如何得到v-model工作呢?
回答by Amresh Venugopal
To use v-modelwith form.parent_id[n]:
v-model与 一起使用form.parent_id[n]:
formshould be a data property.form.parent_idshould be an array.
form应该是数据属性。form.parent_id应该是一个数组。
Then you can do the following:
然后您可以执行以下操作:
<div id="demo">
<div v-for='n in 3'>
<input v-model="form.parent_id[n]">
</div>
<div v-for='n in 3'>
{{ form.parent_id[n] }}
</div>
</div>
by having a vue instance setup like:
通过设置 vue 实例,例如:
var demo = new Vue({
el: '#demo',
data: {
form: {
parent_id: []
}
}
})
Check this fiddlefor a working example.
检查这个小提琴的工作示例。
回答by Mansur Anorboev
Another way achieve this is using bracket notation of accessing object property.
实现此目的的另一种方法是使用访问对象属性的括号表示法。
<div v-for="n in total" class="form-group">
<input type="hidden"
id="input_id"
:name="'input_name_id[' + n + ']'"
v-model="form['parent_id_' + n ]" />
</div>
回答by Atchutha rama reddy Karri
Repeated text filed 10 times and separated v-model for each
重复提交 10 次文本并为每个单独的 v-model
<v-text-field
v-for="(n,index) in 10"
:key="index"
v-model="pricing.name[n]"
color="info"
outline
validate-on-blur
/>
storing data
存储数据
data() {
return {
pricing:{
name: [],
}
}

