I have a array in data()
:
data() {
return {
list: [],
}
},
methods: {
pushData() {
this.list.push({name:'yorn', age: 20});
}
}
Now I want to push to the 'list' array of 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
I want to push to the 'list' array of the following format, The key is
info
list: [ info: [ { name:yorn, age: 20 } ] ]
The above expected result is not a valid JSON
. It should be like below :
list: [{
info: [{
name: yorn,
age: 20
}]
}]
Working Demo :
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});
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(obj, index) in list" :key="index">
<p v-for="(item, i) in obj.info" :key="i">{{ item.name }} </p>
</div>
</div>
You can simply use like below
pushData() {
let data = { info : [{name:'yorn', age: 20}] }
this.list.push(data);
}
Hope this is helpful. :-)
Try altering the pushData
method to have data
parameter
pushData(data) {
this.list.push(data);
}
Invoke the method
this.pushData({name: "john", age: 25});