一、Render函数的作用?
Vue 推荐在绝大多数情况下使用模板来创建你的 HTML。然而在一些场景中,真的需要 JavaScript 的完全编程的能力。这时可以用渲染函数,它比模板更接近编译器。
render 函数和 template 一样都是创建 html 模板的,但是有些场景中用 template 实现起来代码冗长繁琐而且有大量重复,这时候就可以用 render 函数。
以上得知,render 和 template 都是用来创建模板的,如果我在 main.js
中将 render
函数去掉,采用原始的 template
渲染模板会出现什么情况呢?
import Vue from 'vue'
import App from './App'
Vue.config.productionTip = false
new Vue({
el: '#app',
// render: h => h(App),
template: `App`
})
在以上代码执行后,出现了以下错误
vue.runtime.esm.js?2b0e:4560 [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.
大概意思是,我们使用了一个运行时环境的 Vue ,没有包含模板编译器,它给了我们两个解决方案
① 使用完整的、包含模板编译器的 Vue
② 使用 render 来渲染模板
我们先采用第一个方法
1.使用完整的、包含模板编译器的 Vue
我们先进入到引用的 Vue 的 node_modules 中如下图,可以看到默认引用的是 vue.runtime.esm.js
这个是在 Vue.js
的基础上修改过的,它并不包含模板编译器,所以,我们在引入这个“不完整” 的vue基础上再去使用 template
渲染模板就会报错。
我们直接在 main.js
中引入 完整的 vue.js,再使用 template
进行渲染模板,看看会发生什么情况呢?
// 引入完整的vue
import Vue from 'vue/dist/vue'
// import App from './App'
Vue.config.productionTip = false
new Vue({
el: '#app',
// render: h => h(App),
template: `<h1>你好啊</h1>`,
})
最终页面成功展示,没有出现报错,那我们需要思考一个问题,既然可以直接引用完整版的Vue,为什么还要使用“残缺的”呢?
原因是,完整的Vue中包含的模板编译器占据了整个Vue体积的1/3,且模板编译器不宜出现在运行时环境中。
二、如何使用render函数渲染?
我们看到的 render: h => h(App)
其实是简写版本,完整的写法如下
import Vue from 'vue/dist/vue'
// import App from './App'
Vue.config.productionTip = false
new Vue({
el: '#app',
// render: h => h(App),
// 通过 CreateElement 创建元素,它是Vue传入的参数
render(CreateElement) {
return CreateElement('h1','你好啊')
}
})
以上代码精简一下
//精简前
render(CreateElement) {
return CreateElement('h1','你好啊')
}
//精简后
render : h => h('h1','你好啊')
最后传入我们的 APP 组件就可以了,* CreateElement 中的参数如果是组件可以直接传入
import Vue from 'vue/dist/vue'
import App from './App'
Vue.config.productionTip = false
new Vue({
el: '#app',
// render: h => h(App),
render : h => h(App)
})
三、总结
1.vue.js 与 vue.runtime.xxx.js 的区别?
vue.js:完整的vue,包含核心功能 + 模板解析器
vue.runtime.xxx.js:运行时版本,只有核心功能,没有模板解析器
因为vue.runtime.xxx.js 没有模板解析器,所以不能使用 template
配置项,需要使用 render
函数接收到的 CreateElement
函数去指定具体内容。