responsive

Vue is the MVVM framework. When the data changes, the page will be re-rendered. This is vUE responsiveness.

Vue2.xResponse principle

The Object.defineProperty based API converts all properties iterated by the data option into getters/setters, publishing messages to subscribers when data changes, and triggering corresponding listening callbacks. Object.defineproperty does not have the ability to listen on arrays, needs to redefine the stereotype of the array to be responsive, and cannot detect additions and deletions of Object attributes. $delete = Vue. Set (obj, a, 1); data.obj = {… Data.obj, a: 1})

Vue2.x
Function defineReactive(target, key, value) {// Observer (value); Object.defineProperty(target, key, { get() { return value; }, set(newValue) {// Deep listener observer(value); if (newValue ! == value) { value = newValue; updateView(); }}}); } function observer(target) { if (typeof target ! == "object" || target === null) { return target; } if (Array.isArray(target)) { target.__proto__ = arrProto; } for (let key in target) { defineReactive(target, key, target[key]); Const oldAddrayProperty = array.prototype; const arrProto = Object.create(oldAddrayProperty); ["push", "pop", "shift", "unshift", "spluce"].forEach( methodName => (arrProto[methodName] = function() { updateView(); oldAddrayProperty[methodName].call(this, ... arguments); })); Function updateView() {console.log(" updateView "); } // const data = {name: "$", age: 30, info: {address: "B" // nums: [10, 20, 30]}; // Execute a responsive observer(data);Copy the code

Vue3.xResponse principle

Based on Proxy and Reflect to do data hijacking Proxy, can native support array response, also can directly support the object of the new and delete attributes, the only lack of poor compatibility

Vue3.x
const proxyData = new Proxy(data, Const ownKeys = reflect.ownkeys (target) if(ownkeys.includes (key)){get(target,key,receive){// Handle only its own (non-prototype) attributes const ownKeys = reflect.ownkeys (target) if(ownkeys.includes (key)){ Console. log('get',key) // listener} const result = reflect. get(target,key,receive) return result}, set(target, key, val) Reveive){// Duplicate data, Const oldVal = target[key] if(val == oldVal){return true} const result = reflect. set(target, key, val,reveive) console.log('set', key, val) return result }, deleteProperty(target, key){ const result = Reflect.deleteProperty(target,key) console.log('delete property', Key) console.log('result',result) return result}}) const data = {name: "", age: 25, info: {address: "B," / / need depth monitoring}, nums: [10, 20, 30]};Copy the code