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
JavaScript
x
6
1
{
2
a:1,
3
b:2,
4
c:3
5
}
6
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
JavaScript
1
5
1
<div id="app">
2
<button @click="button1()">Button 1</button>
3
<button @click="button2()">Button 2</button>
4
</div>
5
Method
JavaScript
1
31
31
1
new Vue({
2
el: "#app",
3
data: {
4
list:[]
5
},
6
methods: {
7
8
button1(){
9
var b = '0';
10
this.$set(this.list, b, {
11
1:{
12
a: '1',
13
b: '2'
14
}
15
})
16
console.log(this.list);
17
},
18
19
button2(){
20
var b = '0';
21
this.$set(this.list, b,{
22
1:{
23
c: '3'
24
}
25
})
26
console.log(this.list);
27
},
28
29
}
30
})
31
Below there is a jsfiddle link for my code
https://jsfiddle.net/ujjumaki/enj3dwo6/19/
Advertisement
Answer
Hope this works.
JavaScript
1
40
40
1
new Vue({
2
el: "#app",
3
data: {
4
list:[]
5
},
6
methods: {
7
8
button1(){
9
console.log('button 1');
10
11
const b = '0';
12
const restObj=this.list[b] && this.list[b][1]
13
this.$set(this.list, b, {
14
1:{
15
restObj,
16
a: '1',
17
b: '2'
18
}
19
})
20
21
console.log(this.list);
22
},
23
24
button2(){
25
26
const b = '0';
27
const restObj=this.list[b] && this.list[b][1]
28
this.$set(this.list, b,{
29
1:{
30
restObj,
31
c: '3'
32
}
33
})
34
35
console.log(this.list);
36
},
37
38
}
39
})
40