我们在创建vue cli的时候都会遇到这样一个选择
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的不同(只有main.js有不同)
Runtime - Compiler
import Vue from 'vue'
import App from './App'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
components: {
App
},
template: '<App/>'
})
Runtime-only
import Vue from 'vue'
import App from './App'
//底层会把template编译成render函数
//.vue中的template会被vue-template-compiler处理
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
render: h => h(App)
//这里其实是
//render:function(createElement){
createElement('标签',{标签的属性},[内容])
内容内也可以嵌套creatElement
// return createElement('h2',{class:'box'},['hello world'])
//}
//将h作为createlement的别名是Vue生态系统的一个通用惯例
})
也可以理解为
const cpn = {
template: '<div>{{message}}</div>',
data() {
return {
message: '我是message',
}
}
}
//直接传入组件
new Vue({
el: '#app',
render: function(creatment){
return creatment(cpn)
}
})
那么runtime-compiler和runtime-only有什么区别呢?
我们都知道Vue程序运行过程是这样的,即为
- 当我们把一个template传给Vue实例的时候,Vue里面会做一个保存,将其保存到Vue实例下的options
- 将template进行parse(解析),将其解析为ast(abstrcst syntax tree/抽象语法树)
- complie(编译)为render(function)
- 通过render函数将template翻译成vdom node(virtual dom/虚拟dom节点),然后通过虚拟dom节点,将其渲染成虚拟dom树
- 将虚拟dom树渲染成真实dom,即最终显示在UI上面的
即template->(解析)ast->(编译)render->(翻译)vdom->真实DOM
那么
Runtime - Compile经过的过程即为
template->ast->render->vdom->UI
Runtime-only经过的过程即为 (1.性能更高 2.代码量更少)
render-vdom->UI
引用:npm安装vue控制台报错template编译无效
https://blog.csdn.net/Mountains_river/article/details/119238689