Reputation: 568
I am new to VUE and for one project I am trying to update an array passing the object. I have two button which is called BUTTON 1 and BUTTON 2. If you click on BUTTON 1 then it will set an object to list[]
using this.$set
. But when BUTTON 2 is pressed it should update with the new value and should display as
{
a:1,
b:2,
c:3
}
Right now I am using this.$set
for button 2 as well and it removes the previous value then adds the new one as {c:3}
only. Is there a way to add on value using VUE to display { a:1,b:2,c:3}
when BUTTON 2 is clicked.
View
<div id="app">
<button @click="button1()">Button 1</button>
<button @click="button2()">Button 2</button>
</div>
Method
new Vue({
el: "#app",
data: {
list:[]
},
methods: {
button1(){
var b = '0';
this.$set(this.list, b, {
1:{
a: '1',
b: '2'
}
})
console.log(this.list);
},
button2(){
var b = '0';
this.$set(this.list, b,{
1:{
c: '3'
}
})
console.log(this.list);
},
}
})
Below there is a jsfiddle link for my code
https://jsfiddle.net/ujjumaki/enj3dwo6/19/
Upvotes: 0
Views: 139
Reputation: 467
Hope this works.
new Vue({
el: "#app",
data: {
list:[]
},
methods: {
button1(){
console.log('button 1');
const b = '0';
const restObj=this.list[b] && this.list[b][1]
this.$set(this.list, b, {
1:{
...restObj,
a: '1',
b: '2'
}
})
console.log(this.list);
},
button2(){
const b = '0';
const restObj=this.list[b] && this.list[b][1]
this.$set(this.list, b,{
1:{
...restObj,
c: '3'
}
})
console.log(this.list);
},
}
})
Upvotes: 1