日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Vue.js源碼(2):初探ListRendering

下面例子來自官網(wǎng),雖然看上去就比Hello World多了一個v-for,但是內(nèi)部多了好多的處理過程。但是這就是框架,只給你留下最美妙的東西,讓生活變得簡單。

創(chuàng)新互聯(lián)網(wǎng)站建設(shè)由有經(jīng)驗的網(wǎng)站設(shè)計師、開發(fā)人員和項目經(jīng)理組成的專業(yè)建站團(tuán)隊,負(fù)責(zé)網(wǎng)站視覺設(shè)計、用戶體驗優(yōu)化、交互設(shè)計和前端開發(fā)等方面的工作,以確保網(wǎng)站外觀精美、成都做網(wǎng)站、成都網(wǎng)站建設(shè)、成都外貿(mào)網(wǎng)站建設(shè)易于使用并且具有良好的響應(yīng)性。

 
 
  1.  
  2.     
       
    •          
    •           {{ todo.text }} 
    •         
    •  
    •     
     
  
 
 
  1. var vm = new Vue({ 
  2.     el: '#mountNode', 
  3.         data: { 
  4.            todos: [ 
  5.                { text: 'Learn JavaScript' }, 
  6.                { text: 'Learn Vue.js' }, 
  7.                { text: 'Build Something Awesome' } 
  8.            ] 
  9.         } 
  10.     })  

這篇文章將要一起分析:

  • observe array
  • terminal directive
  • v-for指令過程

recap

這里先用幾張圖片回顧和整理下上一篇Vue.js源碼(1):Hello World的背后的內(nèi)容,這將對本篇的compile,link和bind過程的理解有幫助:

copmile階段:主要是得到指令的descriptor 

link階段:實例化指令,替換DOM

 bind階段:調(diào)用指令的bind函數(shù),創(chuàng)建watcher

 用一張圖表示即為:

 observe array

初始化中的merge options,proxy過程和Hello World的過程基本一樣,所以這里直接從observe開始分析。

 
 
  1. // file path: src/observer/index.js 
  2. var ob = new Observer(value) // value = data = {todos: [{message: 'Learn JavaScript'}, ...]}  
 
 
  1. // file path: src/observer/index.js 
  2. export function Observer (value) { 
  3.   this.value = value 
  4.   this.dep = new Dep() 
  5.   def(value, '__ob__', this) 
  6.   if (isArray(value)) {     // 數(shù)組分支 
  7.     var augment = hasProto 
  8.       ? protoAugment 
  9.       : copyAugment         // 選擇增強方法 
  10.     augment(value, arrayMethods, arrayKeys)     // 增強數(shù)組 
  11.     this.observeArray(value) 
  12.   } else {                  // plain object分支 
  13.     this.walk(value) 
  14.   } 
  15. }  

增強數(shù)組

增強(augment)數(shù)組,即對數(shù)組進(jìn)行擴(kuò)展,使其能detect change。這里面有兩個內(nèi)容,一個是攔截數(shù)組的mutation methods(導(dǎo)致數(shù)組本身發(fā)生變化的方法),一個是提供兩個便利的方法$set和$remove。

攔截有兩個方法,如果瀏覽器實現(xiàn)__proto__那么就使用protoAugment,否則就使用copyAugment。

 
 
  1. // file path: src/util/evn.js 
  2. export const hasProto = '__proto__' in {} 
  3.  
  4. // file path: src/observer/index.js 
  5. // 截取原型鏈 
  6. function protoAugment (target, src) { 
  7.   target.__proto__ = src 
  8.  
  9. // file path: src/observer/index.js 
  10. // 定義屬性 
  11. function copyAugment (target, src, keys) { 
  12.   for (var i = 0, l = keys.length; i < l; i++) { 
  13.     var key = keys[i] 
  14.     def(target, key, src[key]) 
  15.   } 
  16. }  

為了更直觀,請看下面的示意圖:

增強之前:

 通過原型鏈攔截: 

 通過定義屬性攔截: 

 在攔截器arrayMethods里面,就是對這些mutation methods進(jìn)行包裝:

  1. 調(diào)用原生的Array.prototype中的方法
  2. 檢查是否有新的值被插入(主要是push, unshift和splice方法)
  3. 如果有新值插入,observe它們
  4. ***就是notify change:調(diào)用observer的dep.notify()

代碼如下: 

 
 
  1. // file path: src/observer/array.js 
  2. ;[ 
  3.   'push', 
  4.   'pop', 
  5.   'shift', 
  6.   'unshift', 
  7.   'splice', 
  8.   'sort', 
  9.   'reverse' 
  10. .forEach(function (method) { 
  11.   // cache original method 
  12.   var original = arrayProto[method] 
  13.   def(arrayMethods, method, function mutator () { 
  14.     // avoid leaking arguments: 
  15.     // http://jsperf.com/closure-with-arguments 
  16.     var i = arguments.length 
  17.     var args = new Array(i) 
  18.     while (i--) { 
  19.       args[i] = arguments[i] 
  20.     } 
  21.     var result = original.apply(this, args) 
  22.     var ob = this.__ob__ 
  23.     var inserted 
  24.     switch (method) { 
  25.       case 'push': 
  26.         inserted = args 
  27.         break 
  28.       case 'unshift': 
  29.         inserted = args 
  30.         break 
  31.       case 'splice': 
  32.         inserted = args.slice(2) 
  33.         break 
  34.     } 
  35.     if (inserted) ob.observeArray(inserted) 
  36.     // notify change 
  37.     ob.dep.notify() 
  38.     return result 
  39.   }) 
  40. })  

observeArray()

知道上一篇的observe(),這里的observeArray()就很簡單了,即對數(shù)組對象都o(jì)bserve一遍,為各自對象生成Observer實例。 

 
 
  1. // file path: src/observer/index.js 
  2. Observer.prototype.observeArray = function (items) { 
  3.   for (var i = 0, l = items.length; i < l; i++) { 
  4.     observe(items[i]) 
  5.   } 
  6. }  

compile

在介紹v-for的compile之前,有必要回顧一下compile過程:compile是一個遞歸遍歷DOM tree的過程,這個過程對每個node進(jìn)行指令類型,指令參數(shù),表達(dá)式,過濾器等的解析。

遞歸過程大致如下:

  1. compile當(dāng)前node
  2. 如果當(dāng)前node沒有terminal directive,則遍歷child node,分別對其compile node
  3. 如果當(dāng)前node有terminal directive,則跳過其child node

這里有個terminal directive的概念,這個概念在Element Directive中提到過:

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

實際上自帶的directive中也有兩個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.

也就是上面遞歸過程中描述的,有terminal directive的node在compile時,會跳過其child node的compile過程。而這些child node將由這個directive單獨compile(partial compile)。

以圖為例,紅色節(jié)點有terminal directive,compile時(綠線)將其子節(jié)點跳過: 

 為什么是v-for和v-if?因為它們會帶來節(jié)點的增加或者刪除。

Compile的中間產(chǎn)物是directive的descriptor,也可能會創(chuàng)建directive來管理的document fragment。這些產(chǎn)物是在link階段時需要用來實例化directive的。從racap中的圖可以清楚的看到,compile過程產(chǎn)出了和link過程怎么使用的它們。那么現(xiàn)在看看v-for的情況:

compile之后,只得到了v-for的descriptor,link時將用它實例化v-for指令。 

 
 
  1. descriptor = { 
  2.     name: 'for', 
  3.     attrName: 'v-for', 
  4.     expression: 'todo in todos', 
  5.     raw: 'todo in todos', 
  6.     def: vForDefinition 
  7. }  

link

Hello World中,link會實例化指令,并將其與compile階段創(chuàng)建好的fragment(TextNode)進(jìn)行綁定。但是本文例子中,可以看到compile過程沒有創(chuàng)建fragment。這里的link過程只實例化指令,其他過程將發(fā)生在v-for指令內(nèi)部。

bind

主要的list rendering的魔法都在v-for里面,這里有FragmentFactory,partial compile還有diff算法(diff算法會在單獨的文章介紹)。

在v-for的bind()里面,做了三件事:

  1. 重新賦值expression,找出alias:"todo in todos"里面,todo是alias,todos才是真正的需要監(jiān)聽的表達(dá)式
  2. 移除
  3. {{todo.text}}
  4. 元素,替換上start和end錨點(anchor)。錨點用來幫助插入最終的li節(jié)點
  5. 創(chuàng)建FragmentFactory:factory會compile被移除的li節(jié)點,得到并緩存linker,后面會用linker創(chuàng)建Fragment 
 
 
  1. // file path: /src/directives/public/for.js 
  2. bind () { 
  3.     // 找出alias,賦值expression = "todos" 
  4.     var inMatch = this.expression.match(/(.*) (?:in|of) (.*)/) 
  5.     if (inMatch) { 
  6.       var itMatch = inMatch[1].match(/\((.*),(.*)\)/) 
  7.       if (itMatch) { 
  8.         this.iterator = itMatch[1].trim() 
  9.         this.alias = itMatch[2].trim() 
  10.       } else { 
  11.         this.alias = inMatch[1].trim() 
  12.       } 
  13.       this.expression = inMatch[2] 
  14.     } 
  15.      
  16.     ... 
  17.      
  18.     // 創(chuàng)建錨點,移除LI元素 
  19.     this.start = createAnchor('v-for-start') 
  20.     this.end = createAnchor('v-for-end') 
  21.     replace(this.el, this.end) 
  22.     before(this.start, this.end) 
  23.  
  24.     ... 
  25.  
  26.     // 創(chuàng)建FragmentFactory 
  27.     this.factory = new FragmentFactory(this.vm, this.el) 
  28.   } 

 

Fragment & FragmentFactory

這里的Fragment,指的不是DocumentFragment,而是Vue內(nèi)部實現(xiàn)的一個類,源碼注釋解釋為:

Abstraction for a partially-compiled fragment. Can optionally compile content with a child scope.

FragmentFactory會compile

  • {{todo.text}}
  • ,并保存返回的linker。在v-for中,數(shù)組發(fā)生變化時,將創(chuàng)建scope,克隆template,即
  • {{todo.text}}
  • ,使用linker,實例化Fragment,然后掛在end錨點上。

    在Fragment中調(diào)用linker時,就是link和bind

  • {{todo.text}}
  • ,和Hello World中一樣,創(chuàng)建v-text實例,創(chuàng)建watcher。 

    scope

    為什么在v-for指令里面可以通過別名(alias)todo訪問循環(huán)變量?為什么有$index和$key這樣的特殊變量?因為使用了child scope。

    還記得Hello World中watcher是怎么識別simplePath的嗎? 

     
     
    1. var getter = new Function('scope', 'return scope.message;') 

    在這里,說白了就是訪問scope對象的todo,$index或者$key屬性。在v-for指令里,會擴(kuò)展其父作用域,本例中父作用域?qū)ο缶褪莢m本身。在調(diào)用factory創(chuàng)建每一個fragment時,都會以下面方式創(chuàng)建合適的child scope給其使用: 

     
     
    1. // file path: /src/directives/public/for.js 
    2. create (value, alias, index, key) { 
    3.     // index是遍歷數(shù)組時的下標(biāo) 
    4.     // value是對應(yīng)下標(biāo)的數(shù)組元素 
    5.     // alias = 'todo' 
    6.     // key是遍歷對象時的屬性名稱 
    7.     ... 
    8.     var parentScope = this._scope || this.vm 
    9.     var scope = Object.create(parentScope) // 以parent scope為原型鏈創(chuàng)建child scope 
    10.     ... 
    11.     withoutConversion(() => { 
    12.       defineReactive(scope, alias, value) // 添加alias到child scope 
    13.     }) 
    14.     defineReactive(scope, '$index', index) // 添加$index到child scope 
    15.     ... 
    16.     var frag = this.factory.create(host, scope, this._frag) 
    17.     ... 
    18.   }  

    detect change

    到這里,基本上“初探”了一下List Rendering的過程,里面有很多概念沒有深入,打算放在后面結(jié)合其他使用這些概念的地方一起在分析,應(yīng)該能體會到其巧妙的設(shè)計。

    ***舉兩個例子,回顧上面的內(nèi)容

    例一: 

     
     
    1. vm.todos[0].text = 'Learn JAVASCRIPT'; 

    改變的是數(shù)組元素中text屬性,由于factory創(chuàng)建的fragment的v-text指令observe todo.text,因此這里直接由v-text指令更新對應(yīng)li元素的TextNode內(nèi)容。

    例二: 

     
     
    1. vm.todos.push({text: 'Learn Vue Source Code'}); 

    增加了數(shù)組元素,v-for指令的watcher通知其做update,diff算法判斷新增了一個元素,于是創(chuàng)建scope,factory克隆template,創(chuàng)建新的fragment,append在#end-anchor的前面,fragment中的v-text指令observe新增元素的text屬性,將值更新到TextNode上。

    更多數(shù)組操作放在diff算法中再看。

    到這里,應(yīng)該對官網(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.


    本文題目:Vue.js源碼(2):初探ListRendering
    本文路徑:http://www.5511xx.com/article/cdicjep.html