What is at the heart of vUE’s responsive principle

To achieve responsiveness in VUe2, we only need to rely on Object.defineProperty for data hijacking to achieve responsiveness

  class Vue {
      constructor(options) {
        this.$options= options; // Data is responsive to this.$data = options.data;
        this.observe(this.$data); // new watcher (); // // by visitingtestProperty triggers the get function, adding the dependency // this.$data.test;
        // new Watcher();
        // this.$data.foo.bar; // new Compile(options.el, this); / / createdif (options.created) {
            options.created.call(this);
        }
      }
    
      observe(value) {
        if(! value || typeof value ! = ="object") {
          return; Keys (value).foreach (key => {this.definereactive (value, key, value[key]); // Delegate attributes from data to vue instances this.proxyData(key); }); } // Define defineReactive(obj, key, val) {this.observe(val); Const dep = new dep (); Object.defineProperty(obj, key, {get() {
            Dep.target && dep.addDep(Dep.target);
            return val;
          },
          set(newVal) {
            if (newVal === val) {
              return;
            }
            val = newVal;
            // console.log(`${key}Properties updated:${val}`); dep.notify(); }}); } proxyData(key) { Object.defineProperty(this, key, {get() {return this.$data[key]
          },
          set(newVal){
            this.$data[key] = newVal; // Dep: Dep {// Dep: Dep {constructor() {// put some dependencies here (watcher) this.deps = []; } addDep(dep) { this.deps.push(dep); }notify() { this.deps.forEach(dep => dep.update()); } } // Watcher class Watcher { constructor(vm, key, cb) { this.vm = vm; this.key = key; this.cb = cb; // Assign the current watcher instance to the Dep static attribute target dep. target = this; this.vm[this.key]; // Trigger getter, add dependency dep. target = null; }update() {
    // console.log("Properties updated"); this.cb.call(this.vm, this.vm[this.key]); }}Copy the code

Observe is an observer that iterates through all attributes of the object and passes the attributes to defineReactive for further processing

DefineReactive defines reactivity within the defineReactive function, const dep = new dep (); The dependency collection is done specifically in get() and in set() to determine if the value of the property has changed. If it has changed, dep.notify() is called to notify the update

Class Dep is designed to manage watcher and watcher is designed to listen for data, to dynamically update data