bbsimonbb
bbsimonbb

Reputation: 28992

How do I do Vue.set() in Vue 3?

As explained here, Vue 3 has moved a bunch of functions that were available on the global Vue instance. They are now named imports. This leads me to think I should be able to do import {set} from 'vue', but I can't. It's not there. Where is set()?

Upvotes: 41

Views: 66276

Answers (2)

pxeba
pxeba

Reputation: 1766

This article talks about reactivity in vue 2 and 3(composition + options API)

You won't need to because vue 3 now uses proxy detection. If you are using a watch and it is not working use the tag deep: true

watch: {
    deep: true
    someObject: {
      handler(newValue, oldValue) {
         x.x()
      },
      
    }
  }

Be aware that deep: true has performance limitations if used on huge objects; use it sparingly.

Upvotes: 6

Marcos Silva
Marcos Silva

Reputation: 2019

You don't need to.

This article will help you to understand why we needed vue.set in the first place. In short, you need it so that you could add a new property to a data object without breaking the reactivity.

With Vue 3, you no longer need to worry about breaking the reactivity. What the article says you shouldn't do in Vue 2, you can now do in Vue 3.

Example on vue 2:

data() {
  return {
    personObject: {
      name: 'John Doe'
    }
  }
},
methods: {
  addBio(bio) {
     this.$set(this.personObject, 'bio', bio)  // this was needed on vue 2
}

Now, on Vue 3 you can add the bio property directly to the object and the object will still be reactive:

methods: {
  addBio(bio) {
     this.personObject['bio'] = bio
  }
}

Upvotes: 94

Related Questions