Vue指令工作原理實現(xiàn)方法
Vue簡介
現(xiàn)在的大前端時代,是一個動蕩紛爭的時代,江湖中已經分成了很多門派,主要以Vue,React還有Angular為首,形成前端框架三足鼎立的局勢。Vue在前端框架中的地位就像曾經的jQuery,由于其簡單易懂、開發(fā)效率高,已經成為了前端工程師必不可少的技能之一。
Vue是一種漸進式JavaScript框架,完美融合了第三方插件和UI組件庫,它和jQuery最大的區(qū)別在于,Vue無需開發(fā)人員直接操作DOM節(jié)點,就可以改變頁面渲染內容,在應用開發(fā)者具有一定的HTML、CSS、JavaScript的基礎上,能夠快速上手,開發(fā)出優(yōu)雅、簡潔的應用程序模塊。
前言
自定義指令是 vue 中使用頻率僅次于組件,其包含 bind 、 inserted 、 update 、 componentUpdated 、 unbind 五個生命周期鉤子。本文將對 vue 指令的工作原理進行相應介紹,從本文中,你將得到:
- 指令的工作原理
- 指令使用的注意事項
基本使用
官網案例:
<div id='app'>
<input type="text" v-model="inputValue" v-focus>
</div>
<script>
Vue.directive('focus', {
// 第一次綁定元素時調用
bind () {
console.log('bind')
},
// 當被綁定的元素插入到 DOM 中時……
inserted: function (el) {
console.log('inserted')
el.focus()
},
// 所在組件VNode發(fā)生更新時調用
update () {
console.log('update')
},
// 指令所在組件的 VNode 及其子 VNode 全部更新后調用
componentUpdated () {
console.log('componentUpdated')
},
// 只調用一次,指令與元素解綁時調用
unbind () {
console.log('unbind')
}
})
new Vue({
data: {
inputValue: ''
}
}).$mount('#app')
</script>
指令工作原理
初始化
初始化全局 API 時,在 platforms/web 下,調用 createPatchFunction 生成 VNode 轉換為真實 DOM 的 patch 方法,初始化中比較重要一步是定義了與 DOM 節(jié)點相對應的 hooks 方法,在 DOM 的創(chuàng)建( create )、激活( avtivate )、更新( update )、移除( remove )、銷毀( destroy )過程中,分別會輪詢調用對應的 hooks 方法,這些 hooks 中一部分是指令聲明周期的入口。
// src/core/vdom/patch.js
const hooks = ['create', 'activate', 'update', 'remove', 'destroy']
export function createPatchFunction (backend) {
let i, j
const cbs = {}
const { modules, nodeOps } = backend
for (i = 0; i < hooks.length; ++i) {
cbs[hooks[i]] = []
// modules對應vue中模塊,具體有class, style, domListener, domProps, attrs, directive, ref, transition
for (j = 0; j < modules.length; ++j) {
if (isDef(modules[j][hooks[i]])) {
// 最終將hooks轉換為{hookEvent: [cb1, cb2 ...], ...}形式
cbs[hooks[i]].push(modules[j][hooks[i]])
}
}
}
// ....
return function patch (oldVnode, vnode, hydrating, removeOnly) {
// ...
}
}
模板編譯
模板編譯就是解析指令參數(shù),具體解構后的 ASTElement 如下所示:
{
tag: 'input',
parent: ASTElement,
directives: [
{
arg: null, // 參數(shù)
end: 56, // 指令結束字符位置
isDynamicArg: false, // 動態(tài)參數(shù),v-xxx[dynamicParams]='xxx'形式調用
modifiers: undefined, // 指令修飾符
name: "model",
rawName: "v-model", // 指令名稱
start: 36, // 指令開始字符位置
value: "inputValue" // 模板
},
{
arg: null,
end: 67,
isDynamicArg: false,
modifiers: undefined,
name: "focus",
rawName: "v-focus",
start: 57,
value: ""
}
],
// ...
}
生成渲染方法
vue 推薦采用指令的方式去操作 DOM ,由于自定義指令可能會修改 DOM 或者屬性,所以避免指令對模板解析的影響,在生成渲染方法時,首先處理的是指令,如 v-model ,本質是一個語法糖,在拼接渲染函數(shù)時,會給元素加上 value 屬性與 input 事件(以 input 為例,這個也可以用戶自定義)。
with (this) {
return _c('div', {
attrs: {
"id": "app"
}
}, [_c('input', {
directives: [{
name: "model",
rawName: "v-model",
value: (inputValue),
expression: "inputValue"
}, {
name: "focus",
rawName: "v-focus"
}],
attrs: {
"type": "text"
},
domProps: {
"value": (inputValue) // 處理v-model指令時添加的屬性
},
on: {
"input": function($event) { // 處理v-model指令時添加的自定義事件
if ($event.target.composing)
return;
inputValue = $event.target.value
}
}
})])
}
生成VNode
vue 的指令設計是方便我們操作 DOM ,在生成 VNode 時,指令并沒有做額外處理。
生成真實DOM
在 vue 初始化過程中,我們需要記住兩點:
- 狀態(tài)的初始化是 父 -> 子,如 beforeCreate 、 created 、 beforeMount ,調用順序是 父 -> 子
- 真實 DOM 掛載順序是 子 -> 父,如 mounted ,這是因為在生成真實 DOM 過程中,如果遇到組件,會走組件創(chuàng)建的過程,真實 DOM 的生成是從子到父一級級拼接。
在 patch 過程中,每此調用 createElm 生成真實 DOM 時,都會檢測當前 VNode 是否存在 data 屬性,存在,則會調用 invokeCreateHooks ,走初創(chuàng)建的鉤子函數(shù),核心代碼如下:
// src/core/vdom/patch.js
function createElm (
vnode,
insertedVnodeQueue,
parentElm,
refElm,
nested,
ownerArray,
index
) {
// ...
// createComponent有返回值,是創(chuàng)建組件的方法,沒有返回值,則繼續(xù)走下面的方法
if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) {
return
}
const data = vnode.data
// ....
if (isDef(data)) {
// 真實節(jié)點創(chuàng)建之后,更新節(jié)點屬性,包括指令
// 指令首次會調用bind方法,然后會初始化指令后續(xù)hooks方法
invokeCreateHooks(vnode, insertedVnodeQueue)
}
// 從底向上,依次插入
insert(parentElm, vnode.elm, refElm)
// ...
}
以上是指令鉤子方法的第一個入口,是時候揭露 directive.js 神秘的面紗了,核心代碼如下:
// src/core/vdom/modules/directives.js
// 默認拋出的都是updateDirectives方法
export default {
create: updateDirectives,
update: updateDirectives,
destroy: function unbindDirectives (vnode: VNodeWithData) {
// 銷毀時,vnode === emptyNode
updateDirectives(vnode, emptyNode)
}
}
function updateDirectives (oldVnode: VNodeWithData, vnode: VNodeWithData) {
if (oldVnode.data.directives || vnode.data.directives) {
_update(oldVnode, vnode)
}
}
function _update (oldVnode, vnode) {
const isCreate = oldVnode === emptyNode
const isDestroy = vnode === emptyNode
const oldDirs = normalizeDirectives(oldVnode.data.directives, oldVnode.context)
const newDirs = normalizeDirectives(vnode.data.directives, vnode.context)
// 插入后的回調
const dirsWithInsert = [
// 更新完成后回調
const dirsWithPostpatch = []
let key, oldDir, dir
for (key in newDirs) {
oldDir = oldDirs[key]
dir = newDirs[key]
// 新元素指令,會執(zhí)行一次inserted鉤子方法
if (!oldDir) {
// new directive, bind
callHook(dir, 'bind', vnode, oldVnode)
if (dir.def && dir.def.inserted) {
dirsWithInsert.push(dir)
}
} else {
// existing directive, update
// 已經存在元素,會執(zhí)行一次componentUpdated鉤子方法
dir.oldValue = oldDir.value
dir.oldArg = oldDir.arg
callHook(dir, 'update', vnode, oldVnode)
if (dir.def && dir.def.componentUpdated) {
dirsWithPostpatch.push(dir)
}
}
}
if (dirsWithInsert.length) {
// 真實DOM插入到頁面中,會調用此回調方法
const callInsert = () => {
for (let i = 0; i < dirsWithInsert.length; i++) {
callHook(dirsWithInsert[i], 'inserted', vnode, oldVnode)
}
}
// VNode合并insert hooks
if (isCreate) {
mergeVNodeHook(vnode, 'insert', callInsert)
} else {
callInsert()
}
}
if (dirsWithPostpatch.length) {
mergeVNodeHook(vnode, 'postpatch', () => {
for (let i = 0; i < dirsWithPostpatch.length; i++) {
callHook(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode)
}
})
}
if (!isCreate) {
for (key in oldDirs) {
if (!newDirs[key]) {
// no longer present, unbind
callHook(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy)
}
}
}
}
對于首次創(chuàng)建,執(zhí)行過程如下:
- oldVnode === emptyNode ,
isCreate為 true ,調用當前元素中所有 bind 鉤子方法。 - 檢測指令中是否存在
inserted鉤子,如果存在,則將 insert 鉤子合并到VNode.data.hooks屬性中。 - DOM 掛載結束后,會執(zhí)行
invokeInsertHook,所有已掛載節(jié)點,如果VNode.data.hooks中存在 insert 鉤子。則會調用,此時會觸發(fā)指令綁定的 inserted 方法。
一般首次創(chuàng)建只會走 bind 和 inserted 方法,而 update 和 componentUpdated 則與 bind 和 inserted 對應。在組件依賴狀態(tài)發(fā)生改變時,會用 VNode diff 算法,對節(jié)點進行打補丁式更新,其調用流程:
- 響應式數(shù)據(jù)發(fā)生改變,調用 dep.notify ,通知數(shù)據(jù)更新。
- 調用 patchVNode ,對新舊 VNode 進行差異化更新,并全量更新當前 VNode 屬性(包括指令,就會進入 updateDirectives 方法)。
- 如果指令存在 update 鉤子方法,調用 update 鉤子方法,并初始化
componentUpdated回調,將 postpatch hooks 掛載到VNode.data.hooks中。 - 當前節(jié)點及子節(jié)點更新完畢后,會觸發(fā)
postpatch hooks,即指令的 componentUpdated 方法
核心代碼如下:
// src/core/vdom/patch.js
function patchVnode (
oldVnode,
vnode,
insertedVnodeQueue,
ownerArray,
index,
removeOnly
) {
// ...
const oldCh = oldVnode.children
const ch = vnode.children
// 全量更新節(jié)點的屬性
if (isDef(data) && isPatchable(vnode)) {
for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode)
if (isDef(i = data.hook) && isDef(i = i.update)) i(oldVnode, vnode)
}
// ...
if (isDef(data)) {
// 調用postpatch鉤子
if (isDef(i = data.hook) && isDef(i = i.postpatch)) i(oldVnode, vnode)
}
}
unbind 方法是在節(jié)點銷毀時,調用 invokeDestroyHook ,這里不做過多描述。
注意事項
使用自定義指令時,和普通模板數(shù)據(jù)綁定, v-model 還是存在一定的差別,如雖然我傳遞參數(shù)( v-xxx='param' )是一個引用類型,數(shù)據(jù)變化時,并不能觸發(fā)指令的 bind 或者 inserted ,這是因為在指令的聲明周期內, bind 和 inserted 只是在初始化時調用一次,后面只會走 update 和 componentUpdated 。
指令的聲明周期執(zhí)行順序為 bind -> inserted -> update -> componentUpdated ,如果指令需要依賴于子組件的內容時,推薦在 componentUnpdated 中寫相應業(yè)務邏輯。
vue 中,很多方法都是循環(huán)調用,如 hooks 方法,事件回調等,一般調用都用 try catch 包裹,這樣做的目的是為了防止一個處理方法報錯,導致整個程序崩潰,這一點在我們開發(fā)過程中可以借鑒使用。
小結
開始看整個 vue 源碼時,對很多細枝末節(jié)方法都不怎么了解,通過梳理具體每個功能的實現(xiàn)時,漸漸能夠看到整個 vue 全貌,同時也能避免開發(fā)使用中的一些坑點。
以上就是Vue指令工作原理實現(xiàn)方法的詳細內容,更多關于Vue指令原理的資料請關注腳本之家其它相關文章!
相關文章
Vue3.0中Ref與Reactive的區(qū)別示例詳析
在vue3中對響應式數(shù)據(jù)的聲明官方給出了ref()和reactive()這兩種方式,這篇文章主要給大家介紹了關于Vue3.0中Ref與Reactive區(qū)別的相關資料,需要的朋友可以參考下2021-07-07
vue路由事件beforeRouteLeave及組件內定時器的清除方法
今天小編就為大家分享一篇vue路由事件beforeRouteLeave及組件內定時器的清除方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09

