Kenstk8
Kenstk8

Reputation: 35

Vue: different options to add a new reactive property?

I am trying to understand the different ways to add a reactive property. I know that I can't add a property directly to the root level so I have a user object set in my data:

data() {
   return {
       user: {
       }
   }
}

from here though is where I get confused because the docs say that using Vue.set is the way to add a new reactive property to the object, so in this example: Vue.set(this.user, 'first_name', 'Bob')

However, I tried a different approach and made a button that triggered a method and inside of it, did the following:

testFunc() {
    let names = ["Bob", "Vin", "Mark"]
    this.user.test_property = names[Math.floor(Math.random() * names.length];
}

and this worked..I tested in the Vue Dev tools and saw the property test_property added to the object and changes to it each time the button was clicked. Why would this work if Vue.set() is the only way to make a new reactive property?

Lastly, I noticed that if I did the following <input v-model="user.other_new_property" />, this tracks changes as well on new properties....not sure why this works either.vue

Upvotes: 3

Views: 173

Answers (2)

小聪聪到此一游
小聪聪到此一游

Reputation: 1294

Of course this.user.test_property can add property test_property to the object. But this property is not reactive.

new Vue({
  el: '#app',
  data() {
    return {
      user: {}
    }
  },
  created() {
    this.user.name = 'a name'
  },
  methods: {
    changeName () {
      this.user.name = 'b name'
    },
    changeAge () {
      this.user.age = '23'
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <p>{{ user.name }}</p>
  <input v-model="user.age" />

  <button @click="changeName">click me to change name</button>
  <button @click="changeAge">click me to change age</button>
</div>

Upvotes: 0

DeathVenom
DeathVenom

Reputation: 394

Looks like you are using Vue v2, with the options api. In that case, you can simply do this.property_name = value; in your method and access it from your template.

Upvotes: 0

Related Questions