v-for循环Vue 2中的动态V模型名称 [英] Dynamic V-model name in a v-for loop Vue 2

查看:75
本文介绍了v-for循环Vue 2中的动态V模型名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发应用程序,并且正在使用 Vue 2 作为javascript框架,在 v-for 循环中,我需要将循环的计数器绑定到元素的 v-model 名称,这是我的代码:

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>  

我需要 n 作为循环的计数器,例如对于第一个元素,它应该是:

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>

name属性绑定可以工作,但是我不知道如何使 v-model 也能正常工作?

the name attribute binding works but I have no idea how to get the v-model working as well?

推荐答案

要在 form.parent_id [n] 中使用 v-model :

  1. form 应该是数据属性.
  2. form.parent_id 应该是一个数组.
  1. form should be a data property.
  2. 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>

通过设置vue实例,例如:

by having a vue instance setup like:

var demo = new Vue({
    el: '#demo',
    data: {
      form: {
        parent_id: []
      }
    }
})

选中此小提琴作为工作示例.

这篇关于v-for循环Vue 2中的动态V模型名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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