Categories
Uncategorized

Invalid Object & Array Manipulations in Vue.js 2

Objects

  let obj = {name: 'Shiva'
             occupation: 'coder'}
delete obj.name
// or delete obj['name']
obj.name = 'Charan'
// or obj['name'] = 'Charan'

This is how you would usually set delete/add/set properties in Javascript. But Vue.js 2 can’t detect the changes if the object is manipulated in this fashion.
For it to be able to detect these changes, use the following.

Vue.set(obj, 'name', 'Shiva')

or

this.$set(obj, 'name', 'Shiva')

Arrays

Similarly for arrays, if we use the following, then Vue.js 2 fails to detect the changes in state.

let arr = [1,2,3,4]
arr[0] = 9

You will have to use the following commands to be able to deal with the above situation and many others.
Vue.js 2 has wrapped methods to help us create work arounds for such issues.

// Vue.set
this.$set(arr, 0, 9)
// or
arr.splice(0, 1, 9)

Wrapped methods

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()