简体   繁体   English

如何动态地将新对象添加到 vue(对象)数据数组 - Vue.js?

[英]How to dynamically add a new object to array of vue (object) data- Vue.js?

I am new to vue.js.我是 vue.js 的新手。 I am working on form.我正在处理表格。 I have a add button in my form, as user click on this button same form field will be added to this form.我的表单中有一个添加按钮,当用户单击此按钮时,相同的表单字段将添加到此表单中。 And user can add as many times he/she want.用户可以添加任意多次。 For this my data is .为此,我的数据是 .

data () {
    return {
      form: [{
          fieldOne: '',
          fieldTwo: '',
      }]
    }
}

As user click on add buton in html my addForm fucntion is called.当用户单击 html 中的添加按钮时,我的 addForm 函数被调用。

addForm() {
 let newObject = {
              fieldOne: '',
              fieldTwo: '',
          }
 this.form.push(newObject); // Gives error.
}

I read about Vue.set .我读到了Vue.set I can easliy add single field or object.我可以轻松添加单个字段或对象。 But I don't know how to add object to my form array.但我不知道如何将对象添加到我的表单数组中。
Please help me out.请帮帮我。

That works .那行得通 What problem are you having?你有什么问题?

markup标记

<div id="vueRoot">
  <button @click="addForm">
    Click Me !
  </button>
  {{form}}
</div>

code代码

var vm = new Vue({
  el : "#vueRoot",
  data : {
    form: [{
      fieldOne: '',
      fieldTwo: '',
    }]
  },
  methods : {
    addForm() {
      let newObject = {
        fieldOne: '',
        fieldTwo: ''
      }
      this.form.push(newObject); // Gives error.
    }
  }
});

Even if you're new and just looking around and trying things out, you'll have more fun if you give real names to things.即使您是新手,只是环顾四周并尝试一下,如果您给事物起真名,您也会获得更多乐趣。 "form" and "fieldOne" will quickly lead into headwreck ! “form”和“fieldOne”将很快陷入困境!

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

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