Vue3.0 was released, a review of the 2.x principle

Vue 2.x response principle

It does several things: data hijacking, collecting dependencies, and distributing updates

  1. Data hijacking: New Vue iterates through data objects, adding getters and setters to all properties with Object.defineProperty
  2. Dependency collection: The process of render that triggers the getter for the data and collects the current Watcher object in the getter
  3. Update: When a setter is issued, the data’s dependent object (watcher object) is iterated over and updated

The data was hijacked

Object attributes are hijacked to make the data observable with Object.defineProperty

class Vue { constructor(options) { observer(options.data); } observer(value) { if (! value || (typeof value ! == 'object')) { return; Keys (value).foreach (key => defineReactive(value, key, value[key])); } defineReactive(obj, key, val) { const dep = new Dep(); DefineProperty (obj, key, {enumerable: true, // The property enumerable is different: Get () {dep.addSub(dep.target); true // Attributes can be modified or deleted. Return val; }, set(newVal) { if (newVal === val) return; dep.notify(newVal); // send out updates}})}} You can see that the main function is the defineReactive function, which implements data hijacking using Object.definePropertyCopy the code

Rely on collecting & distributing updates

So how does Vue know who to notify when data changes? It uses a subscriber Dep, which holds our observer object, notifies the observer when data changes, and the observer completes the update by calling its own UPDATE method.

<! Constructor () {this.newdeps = []} addDep (watcher) {constructor () {this.newdeps = [] Update () {this.newdeps.foreach ((sub) => {sub.update(); this.newdeps.push (watcher); })}} <! Constructor () {constructor () {dep.target = this} update () {constructor () {constructor () {dep.target = this; Console. log(" View updated ~"); // Update view <! --queueWatcher(this) --queueWatcher(this) --queueWatcher(this) --queueWatcher(this) --queueWatcher(this) --queueWatcher(this) --queueWatcher(this) --queueWatcher(this) --queueWatcher(this) --queueWatcher(this) This completes the collection of dependencies. Update notification dependencies when data changes.Copy the code

The above code is the 2.x version of the reactive principle of the code simulation, in vue these several classes are separate files, source address.

In addition, VUE does special processing for arrays, and the principle of array responsiveness I supplement in another article vUE responsive principle – array

Last but not least, old iron please stay, click a "like" then go ~ 🙈