Vue中的编译器
Rio 2023-03-02
Vue
框架
说明
Vue中的编译器笔记总结
# Vue是运行时+编译时
运行时
const { render, h } = Vue
const vnode = h('div', {
class: 'test'
}, 'hello render')
const container = document.querySelector('#app')
// 运行时 调用渲染函数
render(vnode, container)
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
运行时+编译时
const { compile, createApp } = Vue
const html = `<div class="test">hello compile</div>`
const renderFn = compile(html)
const app = createApp({
render: renderFn
})
app.mount("#app")
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
整个Vue渲染通过编译器将模板字符编译成渲染函数,在运行时运行渲染函数。
# 编译器
编译器是一段程序。编译器的作用其实就是将模板template编译为渲染函数
<div @click="handler">click me</div>
1
对于编译器来说,模板就是一个普通的字符串,它会分析该字符 串并生成一个功能与之相同的渲染函数
return () {
return h('div', { onClick: handler }, 'click me')
}
1
2
3
2
3
以.vue文件为例子
其中 <template>
标签里的内容就是模板内容,编译器会把模板内容 编译成渲染函数并添加到 <script>
标签块的组件对象上
<template>
<div @click="handler">click me</div>
</template>
<script>
export default {
data() {/* ... */},
methods: {
handler: () => {/* ... */}
}
// 编译后新添加
// render() { return h('div', { onClick: handler }, 'click me') }
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14