简体   繁体   English

在v-for中使用v-model

[英]Using v-model in v-for

I have the following code: 我有以下代码:

<div v-for="(companion, key) in planForm.companions">        
     <div class="field">
          <label class="label">First Name</label>
          <div class="input-space">
              <input :name="'companion_first_name[' + key + ']'" type="text" v-model="companion.first_name">
          </div>
     </div>

     <div class="field">
        <label class="label">Last Name</label>
        <div class="input-space">
              <input :name="'companion_last_name[' + key + ']'" type="text" v-model="companion.last_name">
        </div>
     </div>
</div>

However the data binding refers to all elements. 但是,数据绑定涉及所有元素。 If I change one input field the others are also changed. 如果我更改一个输入字段,则其他字段也将更改。 But in the name prop of my input element I get the right keys counting from 0 to the last. 但是在输入元素的name属性中,我得到了从0到最后一个计数的右键。


How can I achieve that only the corresponding data changes? 我如何才能实现仅相应的数据更改?

This is how my data structure looks like in Chrome Vue Panel: 这是我的数据结构在Chrome Vue面板中的样子:

companions:Array[3]
 0:Object
  first_name:"Tester"
  last_name:""
 1:Object
  first_name:"Tester"
  last_name:""
 2:Object
  first_name:"Tester"
  last_name:""

Here is a fiddle to better reflect my problem: Fiddle 这里是一个小提琴以更好地反映我的问题: 小提琴

According to your fiddle you are pushing the same object onto the array every time you add one. 根据您的小提琴,您每次添加一个对象时都会将同一对象推入数组。 So you have multiple copies of the same object instead of new independent elements. 因此,您具有同一对象的多个副本,而不是新的独立元素。

This is similar to Vue's requirement that data be a function in components, so that instances of the component don't share the same data object. 这类似于Vue的要求,即data必须是组件中的函数,这样组件的实例才不会共享相同的数据对象。 You can solve your problem the same way: make companionBlueprint a method: 您可以用相同的方法解决您的问题:将companionBlueprint用作方法:

  methods: {
    companionBlueprint() {
      return {
        id: Math.random(),
        first_name: '',
        last_name: ''
      };
    },
    addCompanion() {
      const vm = this;
      const companionBlueprint = vm.companionBlueprint;

      vm.planForm.companions.push(companionBlueprint());
    }
  }

I've added an id to use as the :key in the v-for . 我在v-for添加了一个id用作:key Updated fiddle 更新的小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM