一、问题
使用VueCLI时,我们在main.js文件中,可以看到使用了render函数
new Vue({
el:'#app',
render: h => h(App),
})
但是若在main,js中改成使用模板的方式(如下),此时页面并不渲染
new Vue({
el: '#app',
template: `<App></App>`,
components: {App}
})
控制台页面报错提示
vue.runtime.esm.js?2b0e:619
[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available.
Either pre-compile the templates into render functions, or use the compiler-included build.
根据报错提出两种解决办法:
1.使用render函数
2.使用完整版的Vue
二、为什么使用render函数?
在main.js文件中通过以下方式引入Vue时,此时使用的运行版本的vue( vue.runtime.js),而在该版本中缺少了模板解析器
import Vue from 'vue'
vue.js与vue.runtime.js的区别:
vue.js是完整版的Vue,包含:核心功能 + 模板解析器。
vue.runtime.js是运行版的Vue,只包含:核心功能;没有模板解析器。
因为vue.runtime.js没有模板解析器,所以不能使用template这个配置项,需要使用render函数接收到的createElement函数去指定具体内容。
三、render函数的结构
接受一个函数作为参数
render(createElement) {
return (createElement(App))
}
//createElement函数的功能是创建一个具体的元素
//render(createElement) {
//return (createElement('h1','h1标签'))
//}
用箭头函数形式简写:
render: h=>h(App)