D:\dataTest> vue2 init webpack demo-33
? Project name demo-33
? Project description A Vue.js project
? Author ********
? Vue build (Use arrow keys)
> Runtime + Compiler: recommended for most users
Runtime-only: about 6KB lighter min+gzip, but templates (or any Vue-specific HTML) are ONLY allowed in .vue files - render functions are required elsewhere
如上图所示,在使用 vue-cli 脚手架初始化项目时,会有个选项 Vue build
,可选值有:Runtime + Compiler 和 Runtime-only
为什么上面初始化项目命令中使用的是 vue2 而不是 vue,可以参看:(超详细)在同一设备下安装不同版本的vue脚手架笔记
下面对两者进行简单的理解:
Runtime + Compiler
: recommended for most users- 运行程序+编译器:推荐给大多数用户
- 代码运行过程:template -> ast -> render -> virtual dom -> UI
- (1)先将 template 模板解析成 abstract syntax tree (ast)抽象语法树
- (2)将 ast 编译成 render 函数
- (3)再讲 render 函数翻译成 virtual dom(虚拟DOM)
- (4)最终将 虚拟DOM 渲染到客户端
Runtime-only
: about 6KB lighter min+gzip, but templates (or any Vue-specific HTML) are ONLY allowed in .vue files - render functions are required elsewhere- 仅运行程序: 大约轻6KB的min+gzip,但模板(或任何Vue特定的HTML)只允许在.Vue文件中使用-其他地方需要渲染函数(render)
- 只能识别 render 函数,不能识别 template
- .vue 文件中的 template 是通过 vue-template-compiler 解析成了 render 函数,所以在最后编译出来的运行代码没有 template
- 代码运行过程:render -> virtual dom -> UI
- 从代码运行过程可以看出:Runtime-only 比 Runtime + Compiler 运行更快,性能更好,代码量更少
初始化项目生成的 main.js 中的区别在于:
Runtime + Compiler:
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
Runtime-only:
new Vue({
el: '#app',
router,
render: h => h(App)
})