The core and basic API of Vue two-way data binding is Object.defineProperty. The main internal participants in the two-way data binding process are Obderver, Dep and Watcher. Based on defineProperty and observer mode, two-way data binding is finally realized.

Why collect dependencies?

New Vue({data(){return {name:'zane', gender:' male '}}})Copy the code

If we set this.gender=’ female ‘to Object. DefineProperty, then Vue will perform a virtual DOM comparison as well. This is an intangible waste of some performance, so you need to do dependency collection, interface used to collect, not used to collect.

The process of collecting dependencies

Object.defineProperty

Look directly at the Observer method

Go to dep.js and see the implementation of the dep.Depend () method.

Dep.target, which is a Watcher instantiation object (global), is used in both cases.

Now that you know that dep. target is equal to a Watche object, let’s go back and see what watcher.adddep does.

Note that may be in question here, according to the process as shown in figure, then push into the only global watcher object, according to the current process is like this, but there will be other watcher, but not according to this process into the inside of the subs, if don’t understand now, after reading the entire process such as back to come and look at can understand.

So rely on the collection process is finished, whether it feels very round.

Conclusion:

The dependency collection finally pushes the DEP object passed in the closure in watcher. NewDeps and initializes the push in dep.subs. Vue is the global Watcher object. This. Getter = expOrFn, expOrFn is the core step of later data update page rendering, need to be carefully analyzed.

Step by step:

View update process

DefineReactive set to trigger

Then the vm.patch method will be called to perform the diff process of the virtual DOM to update the interface in real time.

understand

  1. Each component has a global watcher (mandatory)
  2. If you have a Watch or computed operation on some data, you have multiple Watchers
  3. Each rendered data corresponds to a DEP, which is stored in the global WACHER of the corresponding component. Of course, the calculated WACHER also contains the DEP that depends on the calculated data
  4. A DEP typically corresponds to a render watcher, but there can be multiple Watcher if the data has other computational dependencies

Corresponding relations between