DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,864 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Reactivity with Vuejs
Ariel Mejia
Ariel Mejia

Posted on

Reactivity with Vuejs

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.

Top comments (1)

Collapse
 
heykkyu profile image
Jeongkyu Kim

wow thanks!

🌚 Life is too short to browse without dark mode