Ng Sek Long
Ng Sek Long

Reputation: 4786

How to use the Vue component $set to set object in single file component

Following Vue.js tutorial, I read this part here https://v2.vuejs.org/v2/guide/list.html#Object-Change-Detection-Caveats:

var vm = new Vue({
  data: {
    userProfile: {
      name: 'Anika'
    }
  }
})
// It was stated in the tutorial that, the below will add to userProfile
// while making sure userProfile still being reactive
vm.$set(vm.userProfile, 'age', 27)

Nice, would like to try that vm.$set function.

However, my implementation is in a single file component, e.g. something like this:

<script>
export default {
  name: 'Test',
  data() {
    return {
        userProfile: {
          name: 'Anika'
        }
    };
  }
}
</script>

How would I be able to retrive the vm variable above? I have tried the following code but didn't work... With error:

vm.$set is not a function

<script>
let vm = {
  name: 'Test',
  data() {
    return {
       userProfile: {
         name: 'Anika'
       }
    };
  }
}
vm.$set(vm.userProfile, 'age', 27)

export default vm;
</script>

Upvotes: 0

Views: 413

Answers (1)

fixmycode
fixmycode

Reputation: 8506

if you use it inside the context of your component, you just

this.$set(this.userProfile,....)

Upvotes: 2

Related Questions