如果你寫過vue,對v-bind這個指令一定不陌生。
下面我將從源碼層面去帶大家剖析一下v-bind背后的原理。
會從以下幾個方面去探索:
-
v-bind關鍵源碼分析
- v-bind化的屬性統一存儲在哪里:attrsMap與attrsList
- 綁定屬性獲取函數 getBindingAttr 和 屬性操作函數 getAndRemoveAttr
-
v-bind如何處理不同的綁定屬性
- v-bind:key源碼分析
- v-bind:title源碼分析
- v-bind:class源碼分析
- v-bind:style源碼分析
- v-bind:text-content.prop源碼分析
- v-bind的修飾符.camel .sync源碼分析
v-bind關鍵源碼分析
v-bind化的屬性統一存儲在哪里:attrsMap與attrsList
<p v-bind:title="vBindTitle"></p>
假設為p標簽v-bind化了title屬性,我們來分析title屬性在vue中是如何被處理的。
vue在拿到這個html標簽之后,處理title屬性,會做以下幾步:
- 解析html,解析出屬性集合attrs,在start回調中返回
- 在start回調中創建ASTElement,createASTElement(... ,attrs, ...)
- 創建后ASTElement會生成attrsList和attrsMap
至於創建之后是如何處理v-bind:title這種普通的屬性值的,可以在下文的v-bind:src源碼分析中一探究竟。
解析HTML,解析出屬性集合attrs,在start回調中返回
function handleStartTag (match) { ... const l = match.attrs.length const attrs = new Array(l) for (let i = 0; i < l; i++) { const args = match.attrs[i] ... attrs[i] = { name: args[1], value: decodeAttr(value, shouldDecodeNewlines) } } ... if (options.start) { // 在這里上傳到start函數 options.start(tagName, attrs, unary, match.start, match.end) } }
在start回調中創建ASTElement,createASTElement(... ,attrs, ...)
// 解析HMTL parseHTML(template, { ... start(tag, attrs, unary, start, end) { let element: ASTElement = createASTElement(tag, attrs, currentParent) // 注意此處的attrs } })
創建后ASTElement會生成attrsList和attrsMap
// 創建AST元素 export function createASTElement ( tag: string, attrs: Array<ASTAttr>, // 屬性對象數組 parent: ASTElement | void // 父元素也是ASTElement ): ASTElement { // 返回的也是ASTElement return { type: 1, tag, attrsList: attrs, attrsMap: makeAttrsMap(attrs), rawAttrsMap: {}, parent, children: [] } }
attrs的數據類型定義
// 聲明一個ASTAttr 屬性抽象語法樹對象 數據類型 declare type ASTAttr = { name: string; // 屬性名 value: any; // 屬性值 dynamic?: boolean; // 是否是動態屬性 start?: number; end?: number };
綁定屬性獲取函數 getBindingAttr 和 屬性操作函數 getAndRemoveAttr
getBindingAttr及其子函數getAndRemoveAttr在處理特定場景下的v-bind十分有用,也就是”v-bind如何處理不同的綁定屬性“章節很有用。
這里將其列舉出來供下文v-bind:key源碼分析;v-bind:src源碼分析;v-bind:class源碼分析;v-bind:style源碼分析;v-bind:dataset.prop源碼分析源碼分析參照。
export function getBindingAttr ( el: ASTElement, name: string, getStatic?: boolean ): ?string { const dynamicValue = getAndRemoveAttr(el, ':' + name) || getAndRemoveAttr(el, 'v-bind:' + name) if (dynamicValue != null) { return parseFilters(dynamicValue) } else if (getStatic !== false) { const staticValue = getAndRemoveAttr(el, name) if (staticValue != null) { return jsON.stringify(staticValue) } } }
// note: this only removes the attr from the Array (attrsList) so that it // doesn't get processed by processAttrs. // By default it does NOT remove it from the map (attrsMap) because the map is // needed during codegen. export function getAndRemoveAttr ( el: ASTElement, name: string, removeFromMap?: boolean ): ?string { let val if ((val = el.attrsMap[name]) != null) { const list = el.attrsList for (let i = 0, l = list.length; i < l; i++) { if (list[i].name === name) { list.splice(i, 1) // 從attrsList刪除一個屬性,不會從attrsMap刪除 break } } } if (removeFromMap) { delete el.attrsMap[name] } return val }
資源搜索網站大全https://55wd.com 廣州品牌設計公司http://www.maiqicn.com
如何獲取v-bind的值
以下面代碼為例從源碼分析vue是如何獲取v-bind的值。
會從記下幾個場景去分析:
- 常見的key屬性
- 綁定一個普通html attribute:title
- 綁定class和style
- 綁定一個html DOM property:textContent
vBind:{ key: +new Date(), title: "This is a HTML attribute v-bind", class: "{ borderRadius: isBorderRadius }" style: "{ minHeight: 100 + 'px' , maxHeight}" text-content: "hello vue v-bind" }
<div
v-bind:key="vBind.key" v-bind:title="vBind.title" v-bind:class="vBind.class" v-bind:style="vBind.style" v-bind:text-content.prop="vBind.textContent" /> </div>
v-bind:key源碼分析
function processKey (el) { const exp = getBindingAttr(el, 'key') if(exp){ ... el.key = exp; } }
processKey函數中用到了getBindingAttr函數,由於我們用的是v-bind,沒有用:,所以const dynamicValue = getAndRemoveAttr(el, 'v-bind:'+'key');,getAndRemoveAttr(el, 'v-bind:key')函數到attrsMap中判斷是否存在'v-bind:key',取這個屬性的值賦為val並從從attrsList刪除,但是不會從attrsMap刪除,最后將'v-bind:key'的值,也就是val作為dynamicValue,之后再返回解析過濾后的結果,最后將結果set為processKey中將元素的key property。然后存儲在segments中,至於segments是什么,在上面的源碼中可以看到。
v-bind:title源碼分析
title是一種“非vue特殊的”也就是普通的HTML attribute。
function processAttrs(el){ const list = el.attrsList; ... if (bindRE.test(name)) { // v-bind name = name.replace(bindRE, '') value = parseFilters(value) ... addAttr(el, name, value, list[i], ...) } } export const bindRE = /^:|^\.|^v-bind:/ export function addAttr (el: ASTElement, name: string, value: any, range?: Range, dynamic?: boolean) { const attrs = dynamic ? (el.dynamicAttrs || (el.dynamicAttrs = [])) : (el.attrs || (el.attrs = [])) attrs.push(rangeSetItem({ name, value, dynamic }, range)) el.plain = false }
通過閱讀源碼我們看出:對於原生的屬性,比如title這樣的屬性,vue會首先解析出name和value,然后再進行一系列的是否有modifiers的判斷(modifier的部分在下文中會詳細講解),最終向更新ASTElement的attrs,從而attrsList和attrsMap也同步更新。
v-bind:class源碼分析
css的class在前端開發的展現層面,是非常重要的一層。
因此vue在對於class屬性也做了很多特殊的處理。
function transformNode (el: ASTElement, options: CompilerOptions) { const warn = options.warn || baseWarn const staticClass = getAndRemoveAttr(el, 'class') if (staticClass) { el.staticClass = jsON.stringify(staticClass) } const classBinding = getBindingAttr(el, 'class', false /* getStatic */) if (classBinding) { el.classBinding = classBinding } }
在transfromNode函數中,會通過getAndRemoveAttr得到靜態class,也就是;在getBindingAttr得到綁定的class,也就是v-bind:即v-bind:,將ASTElement的classBinding賦值為我們綁定的屬性供后續使用。
v-bind:style源碼分析
style是直接操作樣式的優先級僅次於important,比class更加直觀的操作樣式的一個HTML attribute。
vue對這個屬性也做了特殊的處理。
function transformNode (el: ASTElement, options: CompilerOptions) { const warn = options.warn || baseWarn const staticStyle = getAndRemoveAttr(el, 'style') if (staticStyle) { el.staticStyle = JSON.stringify(parseStyleText(staticStyle)) } const styleBinding = getBindingAttr(el, 'style', false /* getStatic */) if (styleBinding) { el.styleBinding = styleBinding } }
在transfromNode函數中,會通過getAndRemoveAttr得到靜態style,也就是12px'}";在getBindingAttr得到綁定的style,也就是v-bind:即v-bind:class={ minHeight: 100 + 'px' , maxHeight}",其中maxHeight是一個變量,將ASTElement的styleBinding賦值為我們綁定的屬性供后續使用。
v-bind:text-content.prop源碼分析
textContent是DOM對象的原生屬性,所以可以通過prop進行標識。
如果我們想對某個DOM prop直接通過vue進行set,可以在DOM節點上做修改。
下面我們來看源碼。
function processAttrs (el) { const list = el.attrsList ... if (bindRE.test(name)) { // v-bind if (modifiers) { if (modifiers.prop && !isDynamic) { name = camelize(name) if (name === 'innerHtml') name = 'innerHTML' } } if (modifiers && modifiers.prop) { addProp(el, name, value, list[i], isDynamic) } } } export function addProp (el: ASTElement, name: string, value: string, range?: Range, dynamic?: boolean) { (el.props || (el.props = [])).push(rangeSetItem({ name, value, dynamic }, range)) el.plain = false } props?: Array<ASTAttr>;
通過上面的源碼我們可以看出,v-bind:text-content.prop中的text-content首先被駝峰化為textContent(這是因為DOM property都是駝峰的格式),vue還對innerHtml錯誤寫法做了兼容也是有心,之后再通過prop標識符,將textContent屬性增加到ASTElement的props中,而這里的props本質上也是一個ASTAttr。
有一個很值得思考的問題:為什么要這么做?與HTML attribute有何異同?
- 沒有HTML attribute可以直接修改DOM的文本內容,所以需要單獨去標識
- 比通過js去手動更新DOM的文本節點更加快捷,省去了查詢dom然后替換文本內容的步驟
- 在標簽上即可看到我們對哪個屬性進行了v-bind,非常直觀
- 其實v-bind:title可以理解為v-bind:title.attr,v-bind:text-content.prop只不過vue默許不加修飾符的就是HTML attribute罷了
v-bind的修飾符.camel .sync源碼分析
.camel僅僅是駝峰化,很簡單。
但是.sync就不是這么簡單了,它會擴展成一個更新父組件綁定值的v-on偵聽器。
其實剛開始看到這個.sync修飾符我是一臉懵逼的,但是仔細閱讀一下組件的.sync再結合實際工作,就會發現它的強大了。
<Parent v-bind:foo="parent.foo" v-on:updateFoo="parent.foo = $event" ></Parent>
在vue中,父組件向子組件傳遞的props是無法被子組件直接通過this.props.foo = newFoo去修改的。
除非我們在組件this.$emit("updateFoo", newFoo),然后在父組件使用v-on做事件監聽updateFoo事件。若是想要可讀性更好,可以在$emit的name上改為update:foo,然后v-on:update:foo。
有沒有一種更加簡潔的寫法呢???
那就是我們這里的.sync操作符。
可以簡寫為:
<Parent v-bind:foo.sync="parent.foo"></Parent>
然后在子組件通過this.$emit("update:foo", newFoo);去觸發,注意這里的事件名必須是update:xxx的格式,因為在vue的源碼中,使用.sync修飾符的屬性,會自定生成一個v-on:update:xxx的監聽。
下面我們來看源碼:
if (modifiers.camel && !isDynamic) { name = camelize(name) } if (modifiers.sync) { syncGen = genAssignmentCode(value, `$event`) if (!isDynamic) { addHandler(el,`update:${camelize(name)}`,syncGen,null,false,warn,list[i]) // Hyphenate是連字符化函數,其中camelize是駝峰化函數 if (hyphenate(name) !== camelize(name)) { addHandler(el,`update:${hyphenate(name)}`,syncGen,null,false,warn,list[i]) } } else { // handler w/ dynamic event name addHandler(el,`"update:"+(${name})`,syncGen,null,false,warn,list[i],true) } }
通過閱讀源碼我們可以看到:
對於v-bind:foo.sync的屬性,vue會判斷屬性是否為動態屬性。
若不是動態屬性,首先為其增加駝峰化后的監聽,然后再為其增加一個連字符的監聽,例如v-bind:foo-bar.sync,首先v-on:update:fooBar,然后v-on:update:foo-bar。v-on監聽是通過addHandler加上的。
若是動態屬性,就不駝峰化也不連字符化了,通過addHandler(el, update:${name}, ...),老老實實監聽那個動態屬性的事件。
一句話概括.sync:.sync是一個語法糖,簡化v-bind和v-on為v-bind.sync和this.$emit('update:xxx')。為我們提供了一種子組件快捷更新父組件數據的方式。