最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to dynamically add a new object to array of vue (object) data- Vue.js? - Stack Overflow

programmeradmin2浏览0评论

I am new to 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.

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

I read about 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.

I am new to 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.

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

I read about 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.

Share Improve this question edited Jul 14, 2022 at 1:14 tony19 139k23 gold badges277 silver badges347 bronze badges asked Feb 23, 2018 at 11:06 Pulkit AggarwalPulkit Aggarwal 1371 gold badge3 silver badges9 bronze badges 1
  • What error does it give? – Raymond Camden Commented Feb 23, 2018 at 11:27
Add a ment  | 

1 Answer 1

Reset to default 5

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 !

发布评论

评论列表(0)

  1. 暂无评论