Reactive Data Properties in Vue.js

Vue.js is extremely simple to learn and implement. Considering its features like reactivity its the most productive and efficient Javascript framework of the current times.
The great feature of Vue.js is Reactivity. Whenever you update any of the data property in the model, it updates on view instantly. Its a treat to achieve this with a little setup reqired. If you see the below codepen, it will show you how the value is instantly updated on UI when you type in the textbox. This is the reactivity.

Sometimes you may want to update the value of a data property programatically. Thats easy to do when the data property is a String or Number. In such cases assignement to new value will simply work.
For example:

this.msg = "New message!";

See working codepen:

See the Pen Vue Js Reactivity by Arvind Bhardwaj (@arvind) on CodePen.

Most of the times the data property is an object. According to your application logic, there may be any number of items in the object.
According to Vue documentation:

Vue cannot detect property addition or deletion.

Vue does not allow dynamically adding new root-level reactive properties to an already created instance

So this wont work:

var vm = new Vue({
  el: '#app',
  data: {
    msgs: {1: 'One', 2: 'Two', 3: 'Three'}
  }
});

// This will not work
vm.msgs[4] = 'Four';

See the working codepen:

See the Pen Vue Js Reactivity by Arvind Bhardwaj (@arvind) on CodePen.

To add propertied dynamically, vue provides set() function whichj can be used as:

Vue.set(object, key, value)</code>

Inside the component, you can use:

this.$set(this.msgs, 4, 'Four')

So above example will work as:

var vm = new Vue({
  el: '#app',
  data: {
    msgs: {1: 'One', 2: 'Two', 3: 'Three'}
  }
});

// This will work
Vue.set(vm.msgs, 4, 'Four');

If you have need to assign multiple values to an object, you can do as:

this.msgs = Object.assign({}, this.msgs, { 5: 'Five', 6: 'Six' })

If you are using Lodash, you can do as:

this.msgs = _.assign({}, this.msgs, { 5: 'Five', 6: 'Six' })

Final working codepen:

See the Pen Vue Js Reactivity by Arvind Bhardwaj (@arvind) on CodePen.

Written by Arvind Bhardwaj

Arvind is a certified Magento 2 expert with more than 10 years of industry-wide experience.

Website: http://www.webspeaks.in/