When vue2 adds values to data data, why can push bind data, but not directly assign values?

data attribute:

a: {},
b: [],

when getting data from the server in created, it needs to be filled in an and b, because the data needs Filter, so it cannot be assigned directly.

for(let key in response.data.list){
    if(response.data.list[key].type == 2){
        this.a[key] = response.data.list[key]
    }
}

when you change the value of a, the view does not refresh.
read the document and said that it is because there is no property in a that is added by key, to $set.

however, the operation on b has two results.
do this:

for(let key in response.data.list){
    if(response.data.list[key].type == 1){
        this.b.push(response.data.list[key])
    }
}

modify the value of b and the view will be refreshed.
if so:

let index = 0;
for(let key in response.data.list){
    if(response.data.list[key].type == 1){
        this.b[index] = response.data.list[key]
        index PP
    }
}

modify the value of b and the view will not be refreshed.
Why don"t you need $set? for push

Nov.16,2021

vue hijacks the native methods of the array

  

vue data bi-directional binding depends on Object.defineProperty (), and this thing cannot detect changes in the array, so how does your arr [I] change? for vue, it doesn't know, and of course the view is not new. So you have two methods: 1. Save your filtered arrry with an array arr, and then one-time this.b = arr (the pointer of the reference number has changed, and the init, view will be updated for this value). 2. Replace this.b [index] = response.data.list [key] with this.b.push (response.data.list [key])-(the method encapsulated by vue, that is, this method is overwritten on the prototype of each attribute in data, and the push operation will update the corresponding view)

Menu