首先看一下,这两种模式写法上,只有在main.js中不一样
runtime-compiler
//其中App.vue模块中为组件内容
import Vue from 'vue'
import App from './App'
new Vue({
el:'#app',
template:'<App/>',
components:{App}
})
runtime-only
import Vue from 'vue'
import App from './App'
new Vue({
el:'#app',
render:h=>h(App)
})
两种模式下vue程序的运行过程如下
runtime-compiler:vue实例中的template经过解析->ast(抽象语法树)经过编译->render函数->virtual dom(虚拟dom)->UI界面。
runtime-only:render->virtual dom->UI
runtime-only比runtime-compiler少了两个步骤,template的解析过程就没有了,但是这其实是将这个过程的任务交给了vue的一个包:vue-template-compiler,在启动项目时,这个包会将组件中的template转换成render函数。
重点在于这个render函数
render:h=>h(App)(这是ES6的写法),其实相当于
render:funtion(h){
return h(App)
}
其中h函数用createElement更为恰当,以下用createElement描述
createElement('标签',{标签的属性},[标签中的内容])
示例:
new Vue({
el:'#app',
render:function(createElement){
return createElement('h2',{class:'box'},['hello world',...这里还可以写createElement嵌套]);
}
})
或者直接传入组件对象也可,如下
const cpn={
template:`<div>我是组件模板</div>`,
data(){
return {}
}
}
new Vue({
el:'#app',
render:function(createElement){
return createElement(cpn)
}
})
当然最常用的写法就是最开头的那种,import App from './App',其中App也是一个组件,直接传入即可。