Vue: reactivity

来源:互联网 发布:建军大业影评 知乎 编辑:程序博客网 时间:2024/06/06 19:51

Overview

The reactivity system is one of the Vue’s outstanding features. It’s responsible for transforming plain Javascript object to reactive view. When the object(data) is modified, it automatically update the view. The insight of the reactivity system will bring you a better understanding of it.

Principle

Reactivity in Vue from vuejs.org
Vue transform plain javascript object to Virtual DOM so that Vue is faster than traditional framework like Angular which use HTML DOM directly (you have to read more about Virtual DOM for fully understanding why). But how it make it and what Vue does behind the process of rendering? As we new a Vue instance, Vue will call data function to get the plain object, go through it recursively and convert it to getter and setter by using Object.defineProperty (that’s it will not work if you add properties after Vue instance has been created. The object returned by data function will not be called again after that). getter and setter are hoods for data tracking. When properties are accessed or modified, events are fired to notify the watcher (what’s inside the watcher need more in-deep investigation, probably like the watcher is Angular according to watch options) . Watchers will push the DOM-updating (re-render) call to a queue, then Vue will handle the queue when process thread is idle (nextTick).
update queue in Vue
As you can see, Vue handle the changes asynchronously. So watcher will just push one call to the queue even if there are multiple changes at one time. The Render function will be called at the final processing stage. Render function creates Virtual DOM Tree from the properties (that’s why we write render function as createElement), which will be finnally transformed to HTML DOM. With new specification of DOM, transformation from Virtual DOM to HTML DOM is fast (compared to DOM iteration and searching for target in Angular). For how to transform Virtual DOM to HTML DOM, you have to read the source code carefully)

原创粉丝点击