Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
87
rated 0 times [  88] [ 1]  / answers: 1 / hits: 45267  / 8 Years ago, sun, november 6, 2016, 12:00:00

is there a way I can programmatically update the data object / property in vue.js? For example, when my component loads, my data object is:



data: function () {
return {
cars: true,
}
}


And after an event is triggered, I want the data object to look like:



data: function () {
return {
cars: true,
planes: true
}
}


I tried:



<script>

module.exports = {

data: function () {
return {
cars: true
}
},

methods: {
click_me: function () {
this.set(this.planes, true);
}
},

props: []

}

</script>


But this gives me the error this.set is not a function. Can someone help?



Thanks in advance!


More From » vue.js

 Answers
3

Vue does not allow dynamically adding new root-level reactive properties to an already created instance. However, it’s possible to add reactive properties to a nested object, So you may create an object and add a new property like that:


data: function () {
return {
someObject:{
cars: true,
}
}

and add the property with the vm.$set method:


methods: {
click_me: function () {
this.$set(this.someObject, 'planes', true)
}
}

for vue 1.x use Vue.set(this.someObject, 'planes', true)


reactivity


[#60163] Thursday, November 3, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
danalexc

Total Points: 114
Total Questions: 119
Total Answers: 103

Location: Hungary
Member since Wed, Nov 9, 2022
2 Years ago
;