An overview of the
- This paper analyzes the responsivity principle of Vue. In Vue2.0, data proxies are used
Object.difineProperty
Implementation, but that’s only part of the reactive principle. In the source code, Dep and Watcher are also involved, which are responsible for collecting dependencies and creating subscription observers. - The function of Dep is to collect dependencies, specifically where a variable is used, such as in HTML pages, computed, or watch. When this variable changes, everything used with this variable is updated.
- Watcher: Observer, which means where a variable is used, and creates an observer where it is used. When a variable is reassigned and the Dep notification is triggered to update, the observers of the variable are all re-executed and then updated to the page via rendering.
Dep class introduction
- This class provides
Depend (adding subscribers), notify (notifying subscribers of updates), and subs (subscribers)
- Subs is an array containing Watcher instances that indicate where the specified proxy data is used
- Interested students can look at the source code
dep.js
Watcher profile
- This class provides addDep (add to Dep, collect dependencies)
- Interested students can look at the source code
watcher.js
Debug code implementation – simulate the entire process
- structure
DepClass, Wacher
class - Proxy data, the proxy in the following code
"Num"
Data, for example, - Simulated page usage
num
The Dep class is used to collect dependencies (the Depend method). - to
num
Reassignment triggers the Dep to notify the subscriber (subs attribute) of updates - The process here
const proxyObj = {}; Const originObj = {const originObj: 20, //}; Class DepClass {subs = []; // Subscriber target = null; addSub(sub) { this.subs.push(sub); console.log("--sss", this.subs); } depend() {console.log("dep class collects dependencies --"); if (this.target) { this.target.addDep(this); }} notify() {console.log(" Perform notify -> notify subscribers -> re-execute ", this.subs); this.subs.forEach((sub) => sub.run()); }} // Create the Watcher class class Wacher {run() {// The body to perform the update console.log(" update content "); } addDep(dep) {// This means the current Watcher instance dep.addSub(this); Const dep = new DepClass(); dep.target = new Wacher(); Object.defineProperty(proxyObj, "num", { get() { dep.depend(); Return originobj.num; return originobj.num; }, set(newValue) { dep.notify(); Return (originobj.num = newValue); originobj.num = newValue; }}); // Debug code console.log(proxyobj.num); // Where is the proxy Key proxyobj.num = 39; // After replication, DEP notifies subscribers to execute againCopy the code