Vue.js reactivity and track changes.

By on April 17th, 2019 in Javascript, Programming, Vue.js

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

Dynamic reactive object property

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.

<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)!

Read the documentation

One of the first lessons in 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').

Final code

<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.

Vue.js in WordPress Plugin

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

No comments yet. Be the first one!