DIV CSS 佈局教程網

從使用到源碼:全面拆解 Vue 的生命周期與雙向綁定機制
編輯:關於JavaScript     

想把 Vue 用得透徹,光會寫不夠,還得讀懂它的源碼。本文以 Vue 1.0 為例,從生命週期、鉤子函數一路深入到雙向綁定與渲染機制的源碼層面,適合想更進一步理解 Vue 運作原理的讀者。

生命週期

1. 有哪些生命週期接口

 init Created beforeCompile Compiled Ready Attatched Detached beforeDestory destoryed

2. 執行順序

不具備 keep-alive 時:進入為 init→create→beforeCompile→compiled→attached→ready,移出為 beforeDestroy→detached→destroyed。

具備 keep-alive 時:第一次進入仍是完整流程,移出只到 detached;之後每次進入只觸發 attached,移出只觸發 detached。

鉤子函數

3. 有哪些鉤子函數

data、activate、deactivate、canactivate、candeactivate。

4. 執行順序

進入:canactivate→activate→data;移出:candeactivate→deactivate。

5. 父子組件的執行順序

以 A.vue 內含子組件 B 為例(括號內為嵌套的子組件):

不具備 keep-alive 時,移入依序為 canActivate、init、create、beforeCompile、(子組件 init/create/beforeCompile/compile)、compile、activate、data、attached、(子組件 attached)、(子組件 ready)、ready;移出則依序為 canDeactivate、deactivate、beforeDestroy、(子組件 beforeDestroy)、(子組件 destroyed)、detached、(子組件 detached)、destroyed。

具備 keep-alive 時,移入為 canActivate、activate、data、attached、(子組件 attached);移出為 canDeactivate、deactivate、detached、(子組件 detached)。

6. activate 與 data 的執行順序

這涉及鉤子函數的異步 resolve 規則:
1. 若鉤子回傳 Promise,則何時 resolve 取決於該 Promise;
2. 若既不回傳 Promise 也無參數,則同步 resolve;
3. 若不回傳 Promise 但有參數(transition),則等到 transition.next()、abort() 或 redirect() 之一被呼叫才 resolve;
4. 在驗證類鉤子(如 canActivate、canDeactivate 及全域 beforeEach)中,若回傳布林值,也會同步 resolve。

 
 

7. 如何確認界面已更新完成

當生命週期執行到 attached,即代表已完成掛載。

雙向綁定與渲染機制

1. 數據的監聽與觸發(observer)

src 目錄下的 observer 包含三個檔案:array.js、dep.js(實現一個發布訂閱物件)、index.js(利用 Object.defineProperty,為屬性設計特殊的 getter/setter,在 setter 裡觸發函數以達到監聽效果)。核心源碼如下:

 Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { var value = getter ? getter.call(obj) : val if (Dep.target) { dep.depend() if (childOb) { childOb.dep.depend() } if (isArray(value)) { for (var e, i = 0, l = value.length; i < l; i++) { e = value[i] e && e.__ob__ && e.__ob__.dep.depend() } } } return value }, set: function reactiveSetter (newVal) { var value = getter ? getter.call(obj) : val if (newVal === value) { return } if (setter) { setter.call(obj, newVal) } else { val = newVal } childOb = observe(newVal) dep.notify() } })

簡化後的監聽與觸發邏輯如下:

 function notidy(obj,key){ console.log(key+" has changed"); console.log(key+" now is: "+obj[key]); } function ToData(key,val){ var ob=this; Object.defineProperty(ob,key,{ enumerable:true, configurable:true, get:function(){ return val; }, set:function(newval){ if(newval==val){ return; } val=newval; notidy(this,key); } }) }

在 src 目錄下的 directive.js 中,可以看到一系列解析出來的屬性,而 directive 的實例化則在 utils/lifecycle.js 裡。下面這段位於 Directive.prototype._bind:

 var watcher = this._watcher = new Watcher( this.vm, this.expression, this._update, // callback { filters: this.filters, twoWay: this.twoWay, deep: this.deep, preProcess: preProcess, postProcess: postProcess, scope: this._scope } ) // v-model with inital inline value need to sync back to // model instead of update to DOM on init. They would // set the afterBind hook to indicate that. if (this.afterBind) { this.afterBind() } else if (this.update) { this.update(watcher.value) } Directive.prototype.set = function (value) { /* istanbul ignore else */ if (this.twoWay) { this._withLock(function () { this._watcher.set(value) }) } else if (process.env.NODE_ENV !== 'production') { warn( 'Directive.set() can only be used inside twoWay' + 'directives.' ) } }

src 目錄下的 Watch.js 中,可找到 watcher 透過 addDep 方法完成訂閱:

 Watcher.prototype.addDep = function (dep) { var id = dep.id if (!this.newDepIds.has(id)) { this.newDepIds.add(id) this.newDeps.push(dep) if (!this.depIds.has(id)) { dep.addSub(this) } } }

2. Vue 的渲染機制總結

1. 透過 observer 對 data 進行監聽,並提供訂閱某數據項變化的能力;
2. 把 template 解析成一段 document fragment,再解析其中的 directive,得到每個 directive 所依賴的數據項及其更新方法(例如 v-text="message" 解析後,依賴 this.$data.message,對應的視圖更新方法是 node.textContent = this.$data.message);
3. 透過 watcher 把上述兩部分串起來,把 directive 的數據依賴訂閱到對應數據的 observer 上,一旦數據變化便觸發 observer,進而觸發相關的視圖更新方法,最終達到模板原本的關聯效果。

3. Vue 如何改善 v-for 相同數據渲染出錯的問題

未使用 track-by 時,數組渲染內部快取預設以數值本身作為 id。若數組中存在相同的值,透過 id 取到的會是同一個 fragment 片段,最後 insertBefore 操作的是同一個實例,自然不生效。

 <div> <ul id='test'> <li id="child1">child1</li> <li id="child">child2</li> </ul> </div> <script> _element1=document.getElementById('child1'); _element2=document.getElementById('child2'); document.getElementById('test').insertBefore(_element1,_element2); </script>

使用 track-by 的目的,就是自定義這個內部 id,讓數組中數值相同的項目不會選到同一個實例。至於用 track-by='$index' 還是其他唯一 id,則各有取捨:用 $index 時反轉數據不會產生移動操作,而用其他 id 在順序不同時則會有相應的移動。

對象的渲染

對象一般以鍵作為內部快取的 id,同樣可透過 track-by 自定義以提升性能。

 vm.model = { a: { id: 1, val: "model1"}, b: { id: 2, val: "model2"}, c: { id: 3, val: "model2"}, }

列表更新時:

 vm.model = { d: { id: 1, val: "model1"}, e: { id: 2, val: "model2"}, f: { id: 3, val: "model2"} }

以上就是從使用到源碼層面梳理 Vue 生命週期、鉤子函數與雙向綁定機制的完整整理,希望對你有所幫助。若有疑問,歡迎留言交流。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved