将元素添加到具有 v-model 的数组会导致重复

Adding element to array that has v-model causes duplicate

我有一个文本输入字段列表,它是通过 v-for 和 v-model 到数组创建的。我想将元素添加到数组中,从而创建另一个输入字段。

到目前为止一切正常。问题是新的输入字段都以某种方式分配了相同的索引(?),或者发生了其他事情导致它们显示相同的值。

我制作了 this jsfiddle 来展示我的意思。 如果您按下按钮两次,然后尝试编辑其中一个新输入框,那么所有新输入框都将获得编辑后的值。我只希望编辑的输入框显示输入值。

我想我在这里忽略了一些东西。请问有人可以帮忙吗?

Javascript:

new Vue({
  el: '#app',
  data: {
    items: [{name: "one", id: 0}],
    template: {
        name: "two",
        id: 2,
    },
  },
   methods: {
    addRow: function(){
    this.items.push(this.template);
    this.items[this.items.length - 1].id = Math.random();
    }
  }
  })

HTML:

<script src="https://unpkg.com/vue"></script>

<div id="app">
  <div v-for="(item,index) in items" :key="item.id">
  <input v-model="item.name">
  </div>
  <button v-on:click="addRow">
  Add row
  </button>
  <div>Array content: {{items}}</div>
</div>

用法: screenshot of what i'm getting

尝试

   this.items.push({
            name: "two",
             id: 2,
           });

而不是 this.items.push(this.template) 因为 template 属性 是反应性的,它会影响使用它的其他属性

检查这个fiddle

这里的问题是,对于 array.push(declaredObject),您要添加对 template 的引用,因此每个更改都会反映在其所有引用中。

您必须添加一个具有相同属性的新对象,您可以通过多种方式实现,更常见的是Object.assign({}, this.template),最新的是Destructuring objects {...this.template}。所以在你的情况下应该是 this.items.push({...this.template})