Vue2 uses the Object. DefineProperty getter to implement Object listening
Disadvantages of object.defineProperty listener: You cannot listen for attributes to be added or removed; Unable to listen for array index assignment directly Cannot listen to modify array length
Second, to solve the object property listening
Vue provides a set DELETE method for listening on object attributes
3, solve the array listening
Modify the array inheritance relationship, rewrite the method, interception call.
Arr (Array object) -> custom object (its implicit prototype object __proto__ points to Array display prototype object prototype) -> array.prototype
This custom object inherits the Array method overrides the push, pop, shift, unshift, splice, sort, reverse
const ARRAY_METHODS = ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse] const array_methods = Object.create(Array.prototype) ARRAY_METHODS.formEach(method => { array_methods[methos] = function() {console.log(argument) console.log(' arguments are called ') array.from (arguments).foreach (arg => {arguments) Prototyoe [method].apply(this, arguments)}}) console.log(' listen on current arguments ')})Copy the code
-
If the browser supports __proto__, modify the prototype chain
/ /…
If (array.isarray (value)) {value.proto = array_methods //…. }
2. If the browser does not support __proto__, copy the method to the object using the mixed method
// If the listening action occurs, If (array.isarray (value)) {// getOwnPropertyNames returns all of the object's own properties including non-enumerable // Keys returns an enumerable property: true const array_keys = Object.getOwnPropertyNames(array_methods) array_keys.forEach(key => { Object.defineProperty(value, key, { configurable: true, writable: true, enumerable: true, value: array_methods[key] }) }) }Copy the code
Implementation in VUE3
Vue3 uses Proxy objects to intercept objects and customize operations.