Get the App
SLTechnology News&Howtos  ›  Development  › 

How to solve the problem that Vue cannot listen for array changes

Shulou Source: shulou.com Published: 2022-06-03 08:18:29 09月19日 Update

This article mainly explains "how to solve the problem that Vue cannot listen for array changes". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to solve the problem that Vue can't listen for array changes.

Catalogue

1. Vue snooping array

2. Vue cannot listen for array changes.

1. Vue snooping array

Vue can actually listen for array changes, such as

Data () {return {watchArr: [],};}, watchArr (newVal) {console.log ('listening:' + newVal);}, created () {setTimeout () = > {this.watchArr = [1, 2, 3];}, 1000);}

Delete two elements from array subscript 0 and insert an element 3 in subscript 0 using, for example, splice

Data () {return {watchArr: [1,2,3],};}, watchArr (newVal) {console.log ('listening:' + newVal);}, created () {setTimeout (()) = > {this.watchArr.splice (0,2,3);}, 1000);}

The push array can also be monitored.

2. Vue cannot listen for array changes.

But the array cannot be monitored in the following two situations

When setting array items directly using the index, for example, arr [indexofitem] = newValue

When you modify the length of an array, such as arr.length=newLength

For example, it is impossible to listen for array changes.

1. Use the index to modify the array value directly.

Data () {return {watchArr: [{name: 'krry',}],};}, watchArr (newVal) {console.log (' listening:'+ newVal);}, created () {setTimeout (() = > {this.watchArr [0] .name = 'xiaoyue';}, 1000);}

2. Modify the length of the array

If the length is larger than the original array, the subsequent element is set to undefined.

Truncate the redundant elements if the length is less than the original array.

Data () {return {watchArr: [{name: 'krry',}],};}, watchArr (newVal) {console.log (' snooping:'+ newVal);}, created () {setTimeout (()) = > {this.watchArr.length = 5;}, 1000);}, at this point, I believe you have a better understanding of "how to solve the problem that Vue cannot listen for array changes". You might as well do it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Array monitor change element situation length content actual index learning practical deeper subscript two interest practicality actually simple operation method more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Redmi macOS Xiaomi Shulou Tech Info