Javascript 在v-for中使用v-model

Javascript 在v-for中使用v-model,javascript,vue.js,vuejs2,Javascript,Vue.js,Vuejs2,我有以下代码: <div v-for="(companion, key) in planForm.companions"> <div class="field"> <label class="label">First Name</label> <div class="input-space"> <input :name="'compani

我有以下代码:

<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>
这里有一把小提琴更好地反映了我的问题:

根据,每次添加一个对象时,都会将同一个对象推到数组上。因此,您拥有同一对象的多个副本,而不是新的独立元素

这类似于Vue的要求,即
数据
是组件中的一个函数,以便组件的实例不共享相同的数据对象。您可以用同样的方法解决问题:将
companionBlueprint
作为一种方法:

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

      vm.planForm.companions.push(companionBlueprint());
    }
  }
我添加了一个
id
,用作
v-for
中的
:键

根据需要,每次添加一个对象时,都会将同一个对象推到数组上。因此,您拥有同一对象的多个副本,而不是新的独立元素

这类似于Vue的要求,即
数据
是组件中的一个函数,以便组件的实例不共享相同的数据对象。您可以用同样的方法解决问题:将
companionBlueprint
作为一种方法:

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

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

我添加了一个
id
,用作
v-for
中的
:键

很好@Mango add:key in v-for…@RoyJ Right谢谢你的回答,让我更进一步地找到了我的问题。我更新了你的小提琴以反映我的问题。很好@Mango add:key in v-for…@RoyJ Right谢谢你的回答,让我更进一步地找到了我的问题。我更新了你的小提琴以反映我的问题。但是现在我不再有数据绑定了?这就是我在Vue面板中看到的planForm.Compartments
Compartments:Array[2]0:ƒbound companionBlueprint()1:ƒbound companionBlueprint()
数据绑定的工作原理。有什么东西没有像你期望的那样工作吗?由于某种原因,我得到了一个
无法读取未定义的属性“push”
,但看起来我的操作与你的小提琴完全相同。你没有正确引用数组。
vm.planForm.compartments
的某些部分对您的代码设置不正确。老兄,非常感谢!我在请求中遇到了一个问题,
vm.planForm.compartments
返回时未定义。现在一切都很好:)但是现在我不再有数据绑定了?这就是我在Vue面板中看到的planForm.Compartments
Compartments:Array[2]0:ƒbound companionBlueprint()1:ƒbound companionBlueprint()
数据绑定的工作原理。有什么东西没有像你期望的那样工作吗?由于某种原因,我得到了一个
无法读取未定义的属性“push”
,但看起来我的操作与你的小提琴完全相同。你没有正确引用数组。
vm.planForm.compartments
的某些部分对您的代码设置不正确。老兄,非常感谢!我在请求中遇到了一个问题,
vm.planForm.compartments
返回时未定义。现在一切都很好:)