[Vuejs]-Vue: How to use an object in component data?

2πŸ‘

βœ…

This is because b.key does not exist in the initial state of the data object, so Vue was not able to bind to it. The simple solution would be to add a key property to your initial object. You can also use Vue.set to assign the value.

new Vue({
  el: "#app",
  data(){
  	return {
      a: {},
      b: {
      	key: ''
      },
      c: {}
    }
  },
  methods: {
  	changeA(){
    	this.a.key = Math.random();
    },
    changeB(){
    	this.b.key = Math.random();
    },
    changeC(){
    	Vue.set(this.c, 'key', Math.random());
    }
  }
});
body {
  font-family: sans-serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <p><button @click="changeA">Change me!</button> <strong>a.key:</strong> {{ a.key }}</p>
  <p><button @click="changeB">Change me!</button> <strong>b.key:</strong> {{ b.key }}</p>
  <p><button @click="changeC">Change me!</button> <strong>c.key:</strong> {{ c.key }}</p>
</div>

Notice how both b and c are reactive and update instantaneously, while a is not (it does update if you change b or c thanks to Vue re-rendering the app/component).

2πŸ‘

Well this is a limitation in Vue 2.x, and the possible solutions are using Vue.set or this.$set or Object.assign methods for example

this.$set(this.b, 'key', 'value to assign')

OR

Vue.set(this.b, 'key', 'value to assign')

OR

this.b= Object.assign({}, this.b, { key: 'value to assign' })

Note: this issue is already resolved in Vue 3 but mostly people are still on Vue 2x πŸ™‚

πŸ‘€Asim Khan

Leave a comment