溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么使用Vue.js中的List Rendering

發(fā)布時(shí)間:2021-11-17 15:17:05 來(lái)源:億速云 閱讀:142 作者:iii 欄目:web開(kāi)發(fā)

這篇文章主要講解了“怎么使用Vue.js中的List Rendering”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“怎么使用Vue.js中的List Rendering”吧!

recap

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

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

怎么使用Vue.js中的List Rendering

link階段:實(shí)例化指令,替換DOM

怎么使用Vue.js中的List Rendering

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

怎么使用Vue.js中的List Rendering

用一張圖表示即為:

怎么使用Vue.js中的List Rendering

 observe array

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

// 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)之前:

怎么使用Vue.js中的List Rendering

通過(guò)原型鏈攔截:

怎么使用Vue.js中的List Rendering

通過(guò)定義屬性攔截:

怎么使用Vue.js中的List Rendering

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

  1. 調(diào)用原生的Array.prototype中的方法

  2. 檢查是否有新的值被插入(主要是push, unshift和splice方法)

  3. 如果有新值插入,observe它們

  4. ***就是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)行指令類(lèi)型,指令參數(shù),表達(dá)式,過(guò)濾器等的解析。

遞歸過(guò)程大致如下:

  1. compile當(dāng)前node

  2. 如果當(dāng)前node沒(méi)有terminal directive,則遍歷child node,分別對(duì)其compile node

  3. 如果當(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ò):

怎么使用Vue.js中的List Rendering

為什么是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的情況:

怎么使用Vue.js中的List Rendering

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)部。

怎么使用Vue.js中的List Rendering

bind

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

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

  1. 重新賦值expression,找出alias:"todo in todos"里面,todo是alias,todos才是真正的需要監(jiān)聽(tīng)的表達(dá)式

  2. 移除<li v-for="todo in  todos">{{todo.text}}</li>元素,替換上start和end錨點(diǎn)(anchor)。錨點(diǎn)用來(lái)幫助插入最終的li節(jié)點(diǎn)

  3. 創(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)   }

 怎么使用Vue.js中的List Rendering

Fragment & FragmentFactory

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

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。

怎么使用Vue.js中的List Rendering

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給其使用:

怎么使用Vue.js中的List Rendering

// 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上。

感謝各位的閱讀,以上就是“怎么使用Vue.js中的List Rendering”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)怎么使用Vue.js中的List Rendering這一問(wèn)題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI