Vue source code analysis: Watcher class

Watcher is divided into three types:

  • Computed Watcher;
  • User Watcher (listener);
  • Render Watcher

The creation time of the Render Watcher: src/core/instance/lifecycle.js.
The location where the rendering watcher is created: in the mountComponent function of lifecycle.js.
Watcher does not have a static method, because the $watch method uses an instance of Vue. Creation order: calculated attribute Watcher, user Watcher (listener), rendering Watcher

Workflow created by Watcher:

        First, the watcher's constructor is initialized and expOrFn is processed (rendering watcher and listener processing are different).
=>Call this.get(), which calls pushTarget() and then this.getter.call(vm, vm) (for rendering watcher call updateComponent), if it is a user watcher, it will get the value of the attribute (triggering the get operation).
        When the data is updated, the notify() method is called in dep.
=>notify() calls the watcher's update() method.
=> Call queueWatcher() in update().
=> queueWatcher() is a core method that removes duplicate operations and calls flushSchedulerQueue() to refresh the queue and execute the watcher.
And sort the watchers in flushSchedulerQueue(), traverse all watchers, if there is before, trigger the life cycle hook function beforeUpdate, execute watcher.run(), call this.get() internally, and then call this.cb() ( The cb that renders the watcher is noop) The
whole process ends.

View the execution process of rendering watcher

        When data is updated:

  • First, call dep.notify() in the set method of defineReactive.
  • Then call watcher's update()
  • Call queueWatcher() again to store the watch in the queue. If it has already been stored, do not add it repeatedly
  • Then the flushSchedulerQueue() is called in a loop, and flushSchedulerQueue() is called before the end of the message loop through nextTick().
  • Finally call watcher.run(): Get the latest value by calling watcher.get(). If the rendering watcher ends, if it is the user watcher, call this.cb().
            Above, the whole process ends.

Guess you like

Origin blog.csdn.net/weixin_40599109/article/details/108287024