当使用 codegen
中的 generate
函数时,会将 AST
转化为 render
字符串及 staticRenderFns
字符串数组。
为了满足实际执行,我们需要将 render
字符串及 staticRenderFns
字符串数组,对应的转化为 render
函数及 staticRenderFns
函数数组。
1.createFunction
将字符串转化为函数,是利用了 new Function(code)
的形式。
在 to-function.ts
中有以下核心代码:
js
function createFunction(code, errors) {
try {
return new Function(code)
} catch (err: any) {
errors.push({ err, code })
return noop
}
}
export function createCompileToFunctionFn(compile: Function): Function {
const cache = Object.create(null)
return function compileToFunctions(
template: string,
options?: CompilerOptions,
vm?: Component
): CompiledFunctionResult {
options = extend({}, options)
// check cache
const key = options.delimiters
? String(options.delimiters) + template
: template
if (cache[key]) {
return cache[key]
}
// compile
const compiled = compile(template, options)
// turn code into functions
const res: any = {}
const fnGenErrors: any[] = []
res.render = createFunction(compiled.render, fnGenErrors)
res.staticRenderFns = compiled.staticRenderFns.map(code => {
return createFunction(code, fnGenErrors)
})
return (cache[key] = res)
}
}