如果你写过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.lengthconst 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.attrsListfor (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
}
复制代码
如何获取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,也就是class="foo";在getBindingAttr失去绑定的class,也就是v-bind:class="vBind.class"即v-bind:class="{ borderRadius: isBorderRadius }",将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,也就是style="{fontSize: '12px'}";在getBindingAttr失去绑定的style,也就是v-bind:style="vBind.style"即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 nameaddHandler(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')。为咱们提供了一种子组件快捷更新父组件数据的形式。