Vue.js源碼(2):初探List Rendering
下面例子來(lái)自官網(wǎng),雖然看上去就比Hello World多了一個(gè)v-for,但是內(nèi)部多了好多的處理過(guò)程。但是這就是框架,只給你留下最美妙的東西,讓生活變得簡(jiǎn)單。
- <div id="mountNode">
- <ul>
- <li v-for="todo in todos">
- {{ todo.text }}
- </li>
- </ul>
- </div>
- var vm = new Vue({
- el: '#mountNode',
- data: {
- todos: [
- { text: 'Learn JavaScript' },
- { text: 'Learn Vue.js' },
- { text: 'Build Something Awesome' }
- ]
- }
- })
這篇文章將要一起分析:
- observe array
- terminal directive
- v-for指令過(guò)程
recap
這里先用幾張圖片回顧和整理下上一篇Vue.js源碼(1):Hello World的背后的內(nèi)容,這將對(duì)本篇的compile,link和bind過(guò)程的理解有幫助:
copmile階段:主要是得到指令的descriptor
link階段:實(shí)例化指令,替換DOM
bind階段:調(diào)用指令的bind函數(shù),創(chuàng)建watcher
用一張圖表示即為:
observe array
初始化中的merge options,proxy過(guò)程和Hello World的過(guò)程基本一樣,所以這里直接從observe開始分析。
- // file path: src/observer/index.js
- var ob = new Observer(value) // value = data = {todos: [{message: 'Learn JavaScript'}, ...]}
- // file path: src/observer/index.js
- export function Observer (value) {
- this.value = value
- this.dep = new Dep()
- def(value, '__ob__', this)
- if (isArray(value)) { // 數(shù)組分支
- var augment = hasProto
- ? protoAugment
- : copyAugment // 選擇增強(qiáng)方法
- augment(value, arrayMethods, arrayKeys) // 增強(qiáng)數(shù)組
- this.observeArray(value)
- } else { // plain object分支
- this.walk(value)
- }
- }
增強(qiáng)數(shù)組
增強(qiáng)(augment)數(shù)組,即對(duì)數(shù)組進(jìn)行擴(kuò)展,使其能detect change。這里面有兩個(gè)內(nèi)容,一個(gè)是攔截?cái)?shù)組的mutation methods(導(dǎo)致數(shù)組本身發(fā)生變化的方法),一個(gè)是提供兩個(gè)便利的方法$set和$remove。
攔截有兩個(gè)方法,如果瀏覽器實(shí)現(xiàn)__proto__那么就使用protoAugment,否則就使用copyAugment。
- // file path: src/util/evn.js
- export const hasProto = '__proto__' in {}
- // file path: src/observer/index.js
- // 截取原型鏈
- function protoAugment (target, src) {
- target.__proto__ = src
- }
- // file path: src/observer/index.js
- // 定義屬性
- function copyAugment (target, src, keys) {
- for (var i = 0, l = keys.length; i < l; i++) {
- var key = keys[i]
- def(target, key, src[key])
- }
- }
為了更直觀,請(qǐng)看下面的示意圖:
增強(qiáng)之前:
通過(guò)原型鏈攔截:
通過(guò)定義屬性攔截:
在攔截器arrayMethods里面,就是對(duì)這些mutation methods進(jìn)行包裝:
- 調(diào)用原生的Array.prototype中的方法
- 檢查是否有新的值被插入(主要是push, unshift和splice方法)
- 如果有新值插入,observe它們
- ***就是notify change:調(diào)用observer的dep.notify()
代碼如下:
- // file path: src/observer/array.js
- ;[
- 'push',
- 'pop',
- 'shift',
- 'unshift',
- 'splice',
- 'sort',
- 'reverse'
- ]
- .forEach(function (method) {
- // cache original method
- var original = arrayProto[method]
- def(arrayMethods, method, function mutator () {
- // avoid leaking arguments:
- // http://jsperf.com/closure-with-arguments
- var i = arguments.length
- var args = new Array(i)
- while (i--) {
- args[i] = arguments[i]
- }
- var result = original.apply(this, args)
- var ob = this.__ob__
- var inserted
- switch (method) {
- case 'push':
- inserted = args
- break
- case 'unshift':
- inserted = args
- break
- case 'splice':
- inserted = args.slice(2)
- break
- }
- if (inserted) ob.observeArray(inserted)
- // notify change
- ob.dep.notify()
- return result
- })
- })
observeArray()
知道上一篇的observe(),這里的observeArray()就很簡(jiǎn)單了,即對(duì)數(shù)組對(duì)象都o(jì)bserve一遍,為各自對(duì)象生成Observer實(shí)例。
- // file path: src/observer/index.js
- Observer.prototype.observeArray = function (items) {
- for (var i = 0, l = items.length; i < l; i++) {
- observe(items[i])
- }
- }
compile
在介紹v-for的compile之前,有必要回顧一下compile過(guò)程:compile是一個(gè)遞歸遍歷DOM tree的過(guò)程,這個(gè)過(guò)程對(duì)每個(gè)node進(jìn)行指令類型,指令參數(shù),表達(dá)式,過(guò)濾器等的解析。
遞歸過(guò)程大致如下:
- compile當(dāng)前node
- 如果當(dāng)前node沒(méi)有terminal directive,則遍歷child node,分別對(duì)其compile node
- 如果當(dāng)前node有terminal directive,則跳過(guò)其child node
這里有個(gè)terminal directive的概念,這個(gè)概念在Element Directive中提到過(guò):
A big difference from normal directives is that element directives are terminal, which means once Vue encounters an element directive, it will completely skip that element
實(shí)際上自帶的directive中也有兩個(gè)terminal的directive,v-for和v-if(v-else)。
terminal directive
在源碼中找到:
terminal directive will have a terminal link function, which build a node link function for a terminal directive. A terminal link function terminates the current compilation recursion and handles compilation of the subtree in the directive.
也就是上面遞歸過(guò)程中描述的,有terminal directive的node在compile時(shí),會(huì)跳過(guò)其child node的compile過(guò)程。而這些child node將由這個(gè)directive單獨(dú)compile(partial compile)。
以圖為例,紅色節(jié)點(diǎn)有terminal directive,compile時(shí)(綠線)將其子節(jié)點(diǎn)跳過(guò):
為什么是v-for和v-if?因?yàn)樗鼈儠?huì)帶來(lái)節(jié)點(diǎn)的增加或者刪除。
Compile的中間產(chǎn)物是directive的descriptor,也可能會(huì)創(chuàng)建directive來(lái)管理的document fragment。這些產(chǎn)物是在link階段時(shí)需要用來(lái)實(shí)例化directive的。從racap中的圖可以清楚的看到,compile過(guò)程產(chǎn)出了和link過(guò)程怎么使用的它們。那么現(xiàn)在看看v-for的情況:
compile之后,只得到了v-for的descriptor,link時(shí)將用它實(shí)例化v-for指令。
- descriptor = {
- name: 'for',
- attrName: 'v-for',
- expression: 'todo in todos',
- raw: 'todo in todos',
- def: vForDefinition
- }
link
Hello World中,link會(huì)實(shí)例化指令,并將其與compile階段創(chuàng)建好的fragment(TextNode)進(jìn)行綁定。但是本文例子中,可以看到compile過(guò)程沒(méi)有創(chuàng)建fragment。這里的link過(guò)程只實(shí)例化指令,其他過(guò)程將發(fā)生在v-for指令內(nèi)部。
bind
主要的list rendering的魔法都在v-for里面,這里有FragmentFactory,partial compile還有diff算法(diff算法會(huì)在單獨(dú)的文章介紹)。
在v-for的bind()里面,做了三件事:
- 重新賦值expression,找出alias:"todo in todos"里面,todo是alias,todos才是真正的需要監(jiān)聽的表達(dá)式
- 移除<li v-for="todo in todos">{{todo.text}}</li>元素,替換上start和end錨點(diǎn)(anchor)。錨點(diǎn)用來(lái)幫助插入最終的li節(jié)點(diǎn)
- 創(chuàng)建FragmentFactory:factory會(huì)compile被移除的li節(jié)點(diǎn),得到并緩存linker,后面會(huì)用linker創(chuàng)建Fragment
- // file path: /src/directives/public/for.js
- bind () {
- // 找出alias,賦值expression = "todos"
- var inMatch = this.expression.match(/(.*) (?:in|of) (.*)/)
- if (inMatch) {
- var itMatch = inMatch[1].match(/\((.*),(.*)\)/)
- if (itMatch) {
- this.iterator = itMatch[1].trim()
- this.alias = itMatch[2].trim()
- } else {
- this.alias = inMatch[1].trim()
- }
- this.expression = inMatch[2]
- }
- ...
- // 創(chuàng)建錨點(diǎn),移除LI元素
- this.start = createAnchor('v-for-start')
- this.end = createAnchor('v-for-end')
- replace(this.el, this.end)
- before(this.start, this.end)
- ...
- // 創(chuàng)建FragmentFactory
- this.factory = new FragmentFactory(this.vm, this.el)
- }
Fragment & FragmentFactory
這里的Fragment,指的不是DocumentFragment,而是Vue內(nèi)部實(shí)現(xiàn)的一個(gè)類,源碼注釋解釋為:
Abstraction for a partially-compiled fragment. Can optionally compile content with a child scope.
FragmentFactory會(huì)compile<li>{{todo.text}}</li>,并保存返回的linker。在v-for中,數(shù)組發(fā)生變化時(shí),將創(chuàng)建scope,克隆template,即<li>{{todo.text}}</li>,使用linker,實(shí)例化Fragment,然后掛在end錨點(diǎn)上。
在Fragment中調(diào)用linker時(shí),就是link和bind<li>{{todo.text}}</li>,和Hello World中一樣,創(chuàng)建v-text實(shí)例,創(chuàng)建watcher。
scope
為什么在v-for指令里面可以通過(guò)別名(alias)todo訪問(wèn)循環(huán)變量?為什么有$index和$key這樣的特殊變量?因?yàn)槭褂昧薱hild scope。
還記得Hello World中watcher是怎么識(shí)別simplePath的嗎?
- var getter = new Function('scope', 'return scope.message;')
在這里,說(shuō)白了就是訪問(wèn)scope對(duì)象的todo,$index或者$key屬性。在v-for指令里,會(huì)擴(kuò)展其父作用域,本例中父作用域?qū)ο缶褪莢m本身。在調(diào)用factory創(chuàng)建每一個(gè)fragment時(shí),都會(huì)以下面方式創(chuàng)建合適的child scope給其使用:
- // file path: /src/directives/public/for.js
- create (value, alias, index, key) {
- // index是遍歷數(shù)組時(shí)的下標(biāo)
- // value是對(duì)應(yīng)下標(biāo)的數(shù)組元素
- // alias = 'todo'
- // key是遍歷對(duì)象時(shí)的屬性名稱
- ...
- var parentScope = this._scope || this.vm
- var scope = Object.create(parentScope) // 以parent scope為原型鏈創(chuàng)建child scope
- ...
- withoutConversion(() => {
- defineReactive(scope, alias, value) // 添加alias到child scope
- })
- defineReactive(scope, '$index', index) // 添加$index到child scope
- ...
- var frag = this.factory.create(host, scope, this._frag)
- ...
- }
detect change
到這里,基本上“初探”了一下List Rendering的過(guò)程,里面有很多概念沒(méi)有深入,打算放在后面結(jié)合其他使用這些概念的地方一起在分析,應(yīng)該能體會(huì)到其巧妙的設(shè)計(jì)。
***舉兩個(gè)例子,回顧上面的內(nèi)容
例一:
- vm.todos[0].text = 'Learn JAVASCRIPT';
改變的是數(shù)組元素中text屬性,由于factory創(chuàng)建的fragment的v-text指令observe todo.text,因此這里直接由v-text指令更新對(duì)應(yīng)li元素的TextNode內(nèi)容。
例二:
- vm.todos.push({text: 'Learn Vue Source Code'});
增加了數(shù)組元素,v-for指令的watcher通知其做update,diff算法判斷新增了一個(gè)元素,于是創(chuàng)建scope,factory克隆template,創(chuàng)建新的fragment,append在#end-anchor的前面,fragment中的v-text指令observe新增元素的text屬性,將值更新到TextNode上。
更多數(shù)組操作放在diff算法中再看。
到這里,應(yīng)該對(duì)官網(wǎng)上的這句話有更深的理解了:
Instead of a Virtual DOM, Vue.js uses the actual DOM as the template and keeps references to actual nodes for data bindings.