Vue.js reactivity and track changes.

I spent few hours last weekend facing the common issue when you try to modify an object in Vue.js reactivity and track changes. The challenge was to append an array as new property into a reactive Vue object.

After getting the data response via a GET request, I could see the new property print in the console, but the frontend didn’t change, so I thought that something was happening behind the curtain.

Why a new reactive object property dynamiclly created is not really reactive?

<div id="app">
  <p>{{ myObj.first }}</p>
</div>

new Vue({
  el: '#app',
  data: {
    myObj: {}
    
  },
   mounted () {
   this.myObj.first = 'bbb';
   }
})

My thought was that probably I didn’t know Vue as far I believe (…without probably)!

One of the first lesson at my IT course has been “RT#M!”. So that’s what I did:

https://vuejs.org/v2/guide/reactivity.html

Very interesting the Change Detection Caveats section:

Due to the limitations of modern JavaScript (and the abandonment of Object.observe), Vue cannot detect property addition or deletion.

And more:

Vue does not allow dynamically adding new root-level reactive properties to an already created instance.
However, it’s possible to add reactive properties to a nested object using the Vue.set(object, key, value) method.

Go to the Global API section to check the command in deep:

https://vuejs.org/v2/api/#Vue-set

Adds a property to a reactive object, ensuring the new property is also reactive, so triggers view updates. This must be used to add new properties to reactive objects, as Vue cannot detect normal property additions (e.g. this.myObject.newProperty = 'hi').

<div id="app">
  <p>{{ myObj.first }}</p>
</div>

new Vue({
  el: '#app',
  data: {
    myObj: {}
    
  },
   mounted () {
	Vue.set(this.myObj, 'first', 'aaa');
   }
})

I hope this can help you to better understand how Vue.js reactivity works and how to track changes with an object. You can adopt the same approach with arrays since the first argument of Vue.set method can be an Object or an Array.


Check my WordPress Plugin VueSquare. It’s based on a Vue.js UI: Consuming Foursquare API’s you can find the best places to eat, drink, shop, or visit. Search in your area or in any city in the world.