【Vue.js】Common mistakes and solutions when you update array in data property

lamechang
2 min readJan 25, 2021

Array change in data property

I suppose you know the reactive system of Vue.js when you define variables in data property. When you modify an array, perhaps you set an index directly like below.

export default {
data () {
return {
testArray: ['test1', 'test2', 'test3']
}
}
}
this.testArray[1] = 'test4';

Unfortunately, Vue.js can’t detect this kind of changes. The variable itself will be changed, but the reactive system can’t work (e.g. even if this array is used in template and changed, this change won’t be reflected on the browser).

Also, specifying a length of an Array has the same issue 😥

this.testArray.length = 0;

The Causes and Remedies

As written in Vue.js official guide, there are types of changes that Vue cannot detect. Actually I already explained the types in first section😼.

In Vue.js , Array.prototype.splice() is useful. splice() method changes the contents of an array by removing existing elements and/or adding new elements. About the detail, please refer Kasun Dilunika’s below post.

Let’s fix the example I mentioned earlier. It may be difficult to understand since splice() has three variables… Below code will replace second elements to test4 .

export default {
data () {
return {
testArray: ['test1', 'test2', 'test3']
}
}
}
this.testArray.splice(1, 1, 'test')
// Result: [ 'test1', 'test4', 'test3' ]

If you’d like to delete one or more elements without replacement from an array, you can write like down below.

export default {
data () {
return {
testArray: ['test1', 'test2', 'test3']
}
}
}
this.testArray.splice(0, 2)
// Result: [ 'test3' ]

I hope it this will be useful =)

--

--

lamechang

I work for a startup in Shibuya, Tokyo, mainly as full stack engineer.