例子
<ul :class="bindCls" class="list" v-if="isShow"><li v-for="(item,index) in data" @click="clickItem(index)">{{item}}:{{index}}</li></ul>
经过编译,执行 const code = generate(ast, options),生成的 render 代码串如下
with(this){return (isShow) ?_c('ul', {staticClass: "list",class: bindCls},_l((data), function(item, index) {return _c('li', {on: {"click": function($event) {clickItem(index)}}},[_v(_s(item) + ":" + _s(index))])})) : _e()}
_l、_v这类方法定义在src/core/instance/render-helpers/index.js中
// _c就是执行createElement去创建VNodeexport function installRenderHelpers (target: any) {target._o = markOncetarget._n = toNumbertarget._s = toStringtarget._l = renderList // 渲染列表target._t = renderSlottarget._q = looseEqualtarget._i = looseIndexOftarget._m = renderStatictarget._f = resolveFiltertarget._k = checkKeyCodestarget._b = bindObjectPropstarget._v = createTextVNode // 创建文本VNodetarget._e = createEmptyVNode // 创建空的VNodetarget._u = resolveScopedSlotstarget._g = bindObjectListenerstarget._d = bindDynamicKeystarget._p = prependModifier}
在compileToFunctions中会把这个render字符串转换成函数、
定义在src/compiler/to-function.js中
// compileconst compiled = compile(template, options)// turn code into functionsconst res = {}res.render = createFunction(compiled.render, fnGenErrors)function createFunction (code, errors) {try {return new Function(code)} catch (err) {errors.push({ err, code })return noop}}
实际上就是把 render 代码串通过 new Function 的方式转换成可执行的函数,赋值给 vm.options.render,这样当组件通过 vm._render 的时候,就会执行这个 render 函数
generate
const code = generate(ast, options)
generate函数定义在src/compiler/codegen/index.js中
export function generate (ast: ASTElement | void,options: CompilerOptions): CodegenResult {const state = new CodegenState(options)// fix #11483, Root level <script> tags should not be rendered.const code = ast ?(ast.tag === 'script' ? 'null' : genElement(ast, state)) // genElement生成code:'_c("div")'return {render: `with(this){return ${code}}`, // 把code包裹起来staticRenderFns: state.staticRenderFns}}
genElement判断当前AST元素节点的属性执行不同的代码生成函数
export function genElement (el: ASTElement, state: CodegenState): string {if (el.parent) {el.pre = el.pre || el.parent.pre}if (el.staticRoot && !el.staticProcessed) {return genStatic(el, state)} else if (el.once && !el.onceProcessed) {return genOnce(el, state)} else if (el.for && !el.forProcessed) {return genFor(el, state)} else if (el.if && !el.ifProcessed) {return genIf(el, state)} else if (el.tag === 'template' && !el.slotTarget && !state.pre) {return genChildren(el, state) || 'void 0'} else if (el.tag === 'slot') {return genSlot(el, state)} else {// component or elementlet codeif (el.component) {code = genComponent(el.component, el, state)} else {let dataif (!el.plain || (el.pre && state.maybeComponent(el))) {data = genData(el, state)}const children = el.inlineTemplate ? null : genChildren(el, state, true)code = `_c('${el.tag}'${data ? `,${data}` : '' // data}${children ? `,${children}` : '' // children})`}// module transformsfor (let i = 0; i < state.transforms.length; i++) {code = state.transforms[i](el, code)}return code}}
genIf
export function genIf (el: any,state: CodegenState,altGen?: Function,altEmpty?: string): string {el.ifProcessed = true // avoid recursionreturn genIfConditions(el.ifConditions.slice(), state, altGen, altEmpty)}function genIfConditions (conditions: ASTIfConditions,state: CodegenState,altGen?: Function,altEmpty?: string): string {if (!conditions.length) {return altEmpty || '_e()'}// 依次从conditions获取第一个conditionconst condition = conditions.shift()// 生成一段三元运算符的代码if (condition.exp) {return `(${condition.exp})?${genTernaryExp(condition.block)}:${genIfConditions(conditions, state, altGen, altEmpty) // 递归调用自身 如果有多个conditions时就生成多层三元运算逻辑}`} else {return `${genTernaryExp(condition.block)}`}// v-if with v-once should generate code like (a)?_m(0):_m(1)function genTernaryExp (el) {return altGen? altGen(el, state): el.once? genOnce(el, state): genElement(el, state) // 不考虑v-once时最终调用了genElement}}
在例子中只有一个condition,exp为isShow,生成代码如下
return (isShow) ? genElement(el, state) : _e()
genFor
export function genFor (el: any,state: CodegenState,altGen?: Function,altHelper?: string): string {// AST元素节点中获取和for相关的一些属性const exp = el.forconst alias = el.aliasconst iterator1 = el.iterator1 ? `,${el.iterator1}` : ''const iterator2 = el.iterator2 ? `,${el.iterator2}` : ''if (process.env.NODE_ENV !== 'production' &&state.maybeComponent(el) &&el.tag !== 'slot' &&el.tag !== 'template' &&!el.key) {state.warn(`<${el.tag} v-for="${alias} in ${exp}">: component lists rendered with ` +`v-for should have explicit keys. ` +`See https://vuejs.org/guide/list.html#key for more info.`,el.rawAttrsMap['v-for'],true /* tip */)}el.forProcessed = true // avoid recursion// 返回代码字符串return `${altHelper || '_l'}((${exp}),` +`function(${alias}${iterator1}${iterator2}){` +`return ${(altGen || genElement)(el, state)}` +'})'}
在例子中exp是data,alias是item Iterator1是index,生成代码如下
_l((data), function(item, index) {return genElememt(el, state)})
genData & genChildren
回顾例子,它的最外层是 ul,首先执行 genIf,它最终调用了 genElement(el, state) 去生成子节点,注意,这里的 el 仍然指向的是 ul 对应的 AST 节点,但是此时的 el.ifProcessed 为 true,所以命中最后一个 else 逻辑
// component or elementlet codeif (el.component) {code = genComponent(el.component, el, state)} else {let dataif (!el.plain || (el.pre && state.maybeComponent(el))) {data = genData(el, state)}const children = el.inlineTemplate ? null : genChildren(el, state, true)code = `_c('${el.tag}'${data ? `,${data}` : '' // data}${children ? `,${children}` : '' // children})`}// module transformsfor (let i = 0; i < state.transforms.length; i++) {code = state.transforms[i](el, code)}return code
genData
根据AST元素节点的属性构造出一个data字符串,在创建VNode时会作为参数传入
export function genData (el: ASTElement, state: CodegenState): string {let data = '{'// directives first.// directives may mutate the el's other properties before they are generated.const dirs = genDirectives(el, state)if (dirs) data += dirs + ','// keyif (el.key) {data += `key:${el.key},`}// refif (el.ref) {data += `ref:${el.ref},`}if (el.refInFor) {data += `refInFor:true,`}// preif (el.pre) {data += `pre:true,`}// record original tag name for components using "is" attributeif (el.component) {data += `tag:"${el.tag}",`}// module data generation functions// state是CodegenState的实例for (let i = 0; i < state.dataGenFns.length; i++) {data += state.dataGenFns[i](el)}// attributesif (el.attrs) {data += `attrs:${genProps(el.attrs)},`}// DOM propsif (el.props) {data += `domProps:${genProps(el.props)},`}// event handlersif (el.events) {data += `${genHandlers(el.events, false)},`}if (el.nativeEvents) {data += `${genHandlers(el.nativeEvents, true)},`}// slot target// only for non-scoped slotsif (el.slotTarget && !el.slotScope) {data += `slot:${el.slotTarget},`}// scoped slotsif (el.scopedSlots) {data += `${genScopedSlots(el, el.scopedSlots, state)},`}// component v-modelif (el.model) {data += `model:{value:${el.model.value},callback:${el.model.callback},expression:${el.model.expression}},`}// inline-templateif (el.inlineTemplate) {const inlineTemplate = genInlineTemplate(el, state)if (inlineTemplate) {data += `${inlineTemplate},`}}data = data.replace(/,$/, '') + '}'// v-bind dynamic argument wrap// v-bind with dynamic arguments must be applied using the same v-bind object// merge helper so that class/style/mustUseProp attrs are handled correctly.if (el.dynamicAttrs) {data = `_b(${data},"${el.tag}",${genProps(el.dynamicAttrs)})`}// v-bind data wrapif (el.wrapData) {data = el.wrapData(data)}// v-on data wrapif (el.wrapListeners) {data = el.wrapListeners(data)}return data}
state.dataGenFns 的初始化在它的构造器中
export class CodegenState {constructor (options: CompilerOptions) {// ...this.dataGenFns = pluckModuleFunction(options.modules, 'genData')// ...}}
实际上就是获取所有 modules 中的 genData 函数,其中,class module 和 style module 定义了 genData 函数
genData方法定义在src/platforms/web/compiler/modules/class.js中
function genData (el: ASTElement): string {let data = ''if (el.staticClass) {data += `staticClass:${el.staticClass},`}if (el.classBinding) {data += `class:${el.classBinding},`}return data}
在例子中ul AST元素节点定义了el.staticClass和el.classBinding,因此最终生成的data字符串如下
{staticClass: "list",class: bindCls}
genChildren
export function genChildren (el: ASTElement,state: CodegenState,checkSkip?: boolean,altGenElement?: Function,altGenNode?: Function): string | void {const children = el.childrenif (children.length) {const el: any = children[0]// optimize single v-forif (children.length === 1 &&el.for &&el.tag !== 'template' &&el.tag !== 'slot') {const normalizationType = checkSkip? state.maybeComponent(el) ? `,1` : `,0`: ``return `${(altGenElement || genElement)(el, state)}${normalizationType}`}const normalizationType = checkSkip? getNormalizationType(children, state.maybeComponent): 0const gen = altGenNode || genNodereturn `[${children.map(c => gen(c, state)).join(',')}]${normalizationType ? `,${normalizationType}` : ''}`}}
在例子中,li AST 元素节点是 ul AST 元素节点的 children 之一,满足 (children.length === 1 && el.for && el.tag !== ‘template’ && el.tag !== ‘slot’) 条件,因此通过 genElement(el, state) 生成 li AST元素节点的代码,也就回到了之前调用 genFor 生成的代码,把它们拼在一起生成的伪代码如下
return (isShow) ?_c('ul', {staticClass: "list",class: bindCls},_l((data), function(item, index) {return genElememt(el, state)})) : _e()
在例子中,在执行 genElememt(el, state) 的时候,el 还是 li AST 元素节点,el.forProcessed 已为 true,所以会继续执行 genData 和 genChildren 的逻辑。由于 el.events 不为空,在执行 genData 的时候,会执行 如下逻辑
// event handlersif (el.events) {data += `${genHandlers(el.events, false)},`}
genHandlers 的定义在 src/compiler/codegen/events.js 中
export function genHandlers (events: ASTElementHandlers,isNative: boolean): string {const prefix = isNative ? 'nativeOn:' : 'on:'let staticHandlers = ``let dynamicHandlers = ``for (const name in events) {const handlerCode = genHandler(events[name])if (events[name] && events[name].dynamic) {dynamicHandlers += `${name},${handlerCode},`} else {staticHandlers += `"${name}":${handlerCode},`}}staticHandlers = `{${staticHandlers.slice(0, -1)}}`if (dynamicHandlers) {return prefix + `_d(${staticHandlers},[${dynamicHandlers.slice(0, -1)}])`} else {return prefix + staticHandlers}}
对于例子,它最终 genData 生成的 data 字符串如下
{on: {"click": function($event) {clickItem(index)}}}
genChildren 的时候,会执行到如下逻辑
export function genChildren (el: ASTElement,state: CodegenState,checkSkip?: boolean,altGenElement?: Function,altGenNode?: Function): string | void {const children = el.childrenif (children.length) {const el: any = children[0]// optimize single v-forif (children.length === 1 &&el.for &&el.tag !== 'template' &&el.tag !== 'slot') {const normalizationType = checkSkip? state.maybeComponent(el) ? `,1` : `,0`: ``return `${(altGenElement || genElement)(el, state)}${normalizationType}`}const normalizationType = checkSkip? getNormalizationType(children, state.maybeComponent): 0const gen = altGenNode || genNodereturn `[${children.map(c => gen(c, state)).join(',')}]${normalizationType ? `,${normalizationType}` : ''}`}}function genNode (node: ASTNode, state: CodegenState): string {if (node.type === 1) {return genElement(node, state)} else if (node.type === 3 && node.isComment) {return genComment(node)} else {return genText(node)}}
genChildren 的就是遍历 children,然后执行 genNode 方法,根据不同的 type 执行具体的方法
在例子中,li AST 元素节点的 children 是 type 为 2 的表达式 AST 元素节点,那么会执行到 genText(node) 逻辑
export function genText (text: ASTText | ASTExpression): string {return `_v(${text.type === 2? text.expression // no need for () because already wrapped in _s(): transformSpecialNewlines(JSON.stringify(text.text))})`}
因此在例子中,genChildren 生成的代码串如下
[_v(_s(item) + ":" + _s(index))]
和之前拼在一起,最终生成的 code 如下
return (isShow) ?_c('ul', {staticClass: "list",class: bindCls},_l((data), function(item, index) {return _c('li', {on: {"click": function($event) {clickItem(index)}}},[_v(_s(item) + ":" + _s(index))])})) : _e()
