Problem
I have a component with data function that returns an object:
data() => ({
car: {}
})
Car is an empty string, then I want to add values by some interaction (button click):
<div>
<p>{{ car }}</p>
<button @click="addProps">add props</button>
</div>
...
methods: {
addProps() {
this.car.brand = 'Kia'
}
}
Then if I click the button the "car" would not be updated in the UI, this is the reactivity problem, Vue add a specific method to solve this problem using "$set":
...
methods: {
addProps() {
this.$set(this.car, 'car', 'Kia' )
}
}
This is helpful if you have only one property to add, but in many cases is necessary to add more than one property, in this case JS has a function to solve this problem by assing to the same data attribute a new assing object:
methods: {
addProps() {
this.$set(this.car, 'brand', 'Kia' )
this.car = Object.assign({}, this.car, {
'brand': 'Kia',
'year': '2020'
})
}
}
That's all thanks for reading.
Top comments (1)
wow thanks!