Reactivity with Vuejs

Ariel Mejia - Jun 20 '20 - - Dev Community

Problem

I have a component with data function that returns an object:

data() => ({
    car: {}
})
Enter fullscreen mode Exit fullscreen mode

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'
    }
}
Enter fullscreen mode Exit fullscreen mode

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' )
    }
}
Enter fullscreen mode Exit fullscreen mode

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'
        })
    }
}
Enter fullscreen mode Exit fullscreen mode

That's all thanks for reading.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .