MOCKSTACKS
EN
Questions And Answers

More Tutorials









VueJs The array change detection caveats


Introduction


When you try to set a value of an item at a particular index of an array initialized in the data option, vue can't detect the change and does not trigger an update to the state. In order to overcome this caveat you should either use vue's Vue.$set or use Array.prototype.splice method

Examples


Using Vue.$set


In your method or any lifecycle hook that changes the array item at particuar index
new Vue({
 el: '#app',
 data:{
 myArr : ['apple', 'orange', 'banana', 'grapes']
 },
 methods:{
 changeArrayItem: function(){
 //this will not work
 //myArr[2] = 'strawberry';
 //Vue.$set(array, index, newValue)
 this.$set(this.myArr, 2, 'strawberry');
 }
 }
})

Using Array.prototype.splice


You can perform the same change instead of using Vue.$set by using the Array prototype'ssplice()
new Vue({
 el: '#app',
 data:{
 myArr : ['apple', 'orange', 'banana', 'grapes']
 },
 methods:{
 changeArrayItem: function(){
 //this will not work
 //myArr[2] = 'strawberry';
 //Array.splice(index, 1, newValue)
 this.myArr.splice(2, 1, 'strawberry');
}
 }
})

For nested array


If you have nested array, the following can be done
new Vue({
 el: '#app',
 data:{
 myArr : [
 ['apple', 'banana'],
 ['grapes', 'orange']
 ]
 },
 methods:{
 changeArrayItem: function(){
 this.$set(this.myArr[1], 1, 'strawberry');
 }
 }
})

Array of objects containing arrays


new Vue({
 el: '#app',
 data:{
 myArr : [
 {
 name: 'object-1',
 nestedArr: ['apple', 'banana']
 },
 {
 name: 'object-2',
 nestedArr: ['grapes', 'orange']
 }
 ]
 },
 methods:{
 changeArrayItem: function(){
 this.$set(this.myArr[1].nestedArr, 1, 'strawberry');
 }
 }
})


Conclusion

In this page (written and validated by ) you learned about VueJs The array change detection caveats . What's Next? If you are interested in completing VueJs tutorial, your next topic will be learning about: VueJs Using this.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.