实现vue模板解析
Vue 模板解析的基本原理
Vue 的模板解析是将模板字符串转换为渲染函数的过程。核心步骤包括模板编译、AST 生成、优化和代码生成。
模板编译阶段
Vue 使用 vue-template-compiler 将模板字符串编译为抽象语法树(AST)。模板中的指令、插值表达式等会被解析为 AST 节点。
const compiler = require('vue-template-compiler')
const template = `<div>{{ message }}</div>`
const ast = compiler.compile(template, { ast: true }).ast
生成 AST
AST 是模板的抽象表示,包含元素、属性、文本等节点信息。每个节点包含类型、标签名、属性列表、子节点等属性。
{
type: 1,
tag: 'div',
attrsList: [],
children: [{
type: 2,
expression: '_s(message)',
text: '{{ message }}'
}]
}
优化 AST
Vue 会对 AST 进行静态分析,标记静态节点。这些节点在后续更新中可以跳过比对,提升性能。
function markStatic(root) {
if (root.type === 1) {
root.static = isStatic(root)
root.children.forEach(child => markStatic(child))
}
}
生成渲染函数
将优化后的 AST 转换为可执行的渲染函数代码。这个过程会生成 _c(创建元素)、_v(创建文本)等辅助函数。
function generate(ast) {
const code = ast ? genElement(ast) : '_c("div")'
return new Function(`with(this){return ${code}}`)
}
运行时处理
生成的渲染函数在运行时执行,创建虚拟 DOM。Vue 的响应式系统会追踪依赖,在数据变化时重新执行渲染函数。
function render() {
return _c('div', [_v(_s(message))])
}
自定义解析器
可以通过自定义编译器选项实现特殊模板解析需求。例如处理自定义指令或修改解析规则。
const { compile } = require('vue-template-compiler')
const options = {
directives: {
custom: (node, directiveMeta) => {
// 处理自定义指令
}
}
}
compile(template, options)
服务端渲染处理
服务端渲染需要特殊处理模板解析,避免客户端特有的行为。Vue 提供了服务端渲染的编译方法。
const { createBundleRenderer } = require('vue-server-renderer')
const renderer = createBundleRenderer(serverBundle, {
template: fs.readFileSync('./index.template.html', 'utf-8')
})
以上步骤展示了 Vue 模板从字符串到渲染函数的完整解析流程。实际应用中,Vue CLI 等工具已经封装了这些过程,开发者通常只需要编写模板即可。







