search

Home  >  Q&A  >  body text

Push data and keys into array in Vue.js

I have an array in data():

data()  {
  return {
    list: [],
 }
},

methods: {
  pushData() {
     this.list.push({name:'yorn', age: 20});
  }
}

Now I want to push to the 'list' array in the following format, the key is info:

list [
     info [
     {
       name:yorn,
       age: 20
     }
  ]
 ]

I'm new to vuejs and javascript, so I need everyone's help. Please give me your opinion. Thanks

P粉564192131P粉564192131276 days ago382

reply all(2)I'll reply

  • P粉990008428

    P粉9900084282024-02-26 12:46:26

    Try changing the pushData method to have the data parameter

    pushData(data) {
     this.list.push(data);
    }

    Calling method

    this.pushData({name: "john", age: 25});

    reply
    0
  • P粉004287665

    P粉0042876652024-02-26 10:21:41

    The above expected result is not a valid JSON. It should look like below:

    list: [{
        info: [{
            name: yorn,
            age: 20
        }]
    }]

    Working Demonstration:

    new Vue({
      el: '#app',
      data: {
        list: []
      },
      mounted() {
        this.pushData();
      },
      methods: {
        pushData() {
          this.list.push({info : [{name:'yorn', age: 20}] });
          // Or you can also use below one.
          // this.list[0].info.push({name:'yorn', age: 20});
        }
      }
    })
    
    

    {{ item.name }}

    reply
    0
  • Cancelreply