What is a response?

You manipulate an object, and the object gives you a certain response, and that’s a response. So the data response is that you manipulate the data and the data reacts accordingly.

For example, if you change the data in vue, the data in the view will be changed directly.

So how does VUE implement data responsive?

Implement the three main roles in the data response

  • purpleObserverandDep:
    1. ObserverIs to add to the property of an objectgeteterandsetterTo collect dependencies and dispatch updates.
    2. DepIs to collect the dependencies of the current object. When the object’s data changes,dep.notifynoticewatcherChange the data
  • The blueWatcher: Observer object, instance hasRendering watcher (render water).Computed Watcher.Listener watcher (user watcher)Three kinds of

Of course, the description of the text is difficult to understand their relationship and function, you can see the following picture. Reactive can be understood as the purple part in Figure 1

As you can see, a property corresponds to a Dep and possibly multiple Components (because this property can be used in multiple places), and each Component corresponds to a Watch. Dep is the intermediate between the property and Watch. In other professional terms,Dep helps us manage dependencies

The idea is that the Observer and Dep monitor and proxy incoming data. When the data is sent differently, they call dep.notify to notify the Watcher. The Watcher receives the notification, changes the data based on the notification, and renders the data to the view.

The core code

/ * * *@name Vue data bidirectional binding (responsive system) implementation principle */

The // observe method iterates over and wraps the object properties
function observe(target) {
  // If target is an object, iterate over it
  if (target && typeof target === "Object") {
    Object.keys(target).forEach((key) = > {
      // defineReactive will install "listener" to the target attributedefineReactive(target, key, target[key]); }); }}// Define the defineReactive method
function defineReactive(target, key, val) {
  const dep = new Dep();
  // The property value may also be of type Object, in which case you need to call Observe for recursive traversal
  observe(val);
  // Install a listener for the current property
  Object.defineProperty(target, key, {
    / / can be enumerated
    enumerable: true.// Not configurable
    configurable: false.get: function () {
      return val;
    },
    // The listener function
    set: function (value) { dep.notify(); }}); }class Dep {
  constructor() {
    this.subs = [];
  }

  addSub(sub) {
    this.subs.push(sub);
  }

  notify() {
    this.subs.forEach((sub) = >{ sub.update(); }); }}Copy the code