v-for 循环 Vue 2 中的动态 V 模型名称 [英] Dynamic V-model name in a v-for loop Vue 2
问题描述
我正在开发一个应用程序,我使用 Vue 2
作为 javascript 框架,在 v-for
循环内,我需要将循环的计数器绑定到元素的 v-model
名称,这是我的代码:
<input type="hidden" id="input_id" :name="'input_name_id[' + n + ']'" v-model="form.parent_id_n"/>
我需要 n
作为循环的计数器,例如对于第一个元素它应该是:
<input type="hidden" id="input_id" :name="'input_name_id[1]" v-model="form.parent_id_1"/>
name 属性
绑定有效,但我不知道如何让 v-model
也有效?
使用 v-model
和 form.parent_id[n]
:
form
应该是一个数据属性.form.parent_id
应该是一个数组.
然后您可以执行以下操作:
<input v-model="form.parent_id[n]">{{ form.parent_id[n] }}
通过设置 vue 实例,例如:
var demo = new Vue({el: '#demo',数据: {形式: {parent_id: []}}})
检查这个 fiddle 以获得一个工作示例.
I am developing an application and I am using Vue 2
as the javascript framework,
inside a v-for
loop I need the counter of the loop to be bound to the v-model
name of the elements, this my code:
<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 n
to be the counter of the loop, for example for the first element it should be:
<div class="form-group">
<input type="hidden" id="input_id" :name="'input_name_id[1]" v-model="form.parent_id_1" />
</div>
the name attribute
binding works but I have no idea how to get the v-model
working as well?
To use v-model
with form.parent_id[n]
:
form
should be a data property.form.parent_id
should be an array.
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:
var demo = new Vue({
el: '#demo',
data: {
form: {
parent_id: []
}
}
})
Check this fiddle for a working example.
这篇关于v-for 循环 Vue 2 中的动态 V 模型名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!