1. Objects can override setters and getters to add listening logic, but arrays cannot override setters and getters.
However, we can make use of the array every time we need to go through its API, so we can rewrite the prototype API. In SRC /core/ Observer/Array we can see which API has been rewritten. The purpose of the rewrite is to inform the corresponding dependent instance to rerender when the array changes
function observerArray() { const arrayProto = Array.prototype; export const arrayMethods = Object.create(arrayProto); const methodsToPatch = [ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ] methodsToPatch.forEach(function (method) { Object.defineProperty(arrayMethods, method, { value: function mutator(... args) { let ob = this.__ob__; ob.dep.notify(); return arrayMethods.apply(this, args); }, writable: true, configurable: true }) } )}Copy the code
2. Considering this, we understand how to implement responsiveness when the value of an attribute is an array. You may have the same question as me at this time
export default {
data() {
return {
a: 1,
b: 2,
c: []
}
}
}
Copy the code
When an instance is initialized, a, B, and C will all have the corresponding deP set. At this time, it is known which instances will access C. When we change the value of A through this.a = 3, the setter for A will be triggered. This.c = 4 will also trigger the setter for C, but when we call this.a.ush (1), this will not be heard, so we’ll override the array API to implement array responsiveness
3. To handle arrays, you observer can change to this
class Observe {
constructor(value) {
this.value = value;
if (Array.isArray(value)) {
observerArray();
}
this.walk(value);
}
walk(obj) {
const keys = Object.keys(obj);
for(let i = 0;i < keys.length;i++) {
defineReactive(obj, keys[i], obj[keys[i]]);
}
}
}
Copy the code
Conclusion: Arrays collect dependencies in the same way as objects, but the dependency trigger update mechanism is implemented by overriding the prototype, and as you can see from methodsToPatch above, you can’t listen to arrays by changing their subscripts or by changing their length