Search code examples
vue.jsvuejs3

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()?


Solution

  • 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
      }
    }