大部分情况下我们都会使用template来创建html,开发体验会更好,但并不是每个时候使用它来创建 html 都是最佳的,所以官方提供了接近原生构建html的render()函数,让开发者能够依据自己的情况选择更好的构建方式。
有些同学会问,到底何时选择template或者render(),我的回答是,你应该两者都得掌握,template 有它的局限性,render()函数可以是对它的补充,各有优缺点,你把他们使用在正确的地方,就能更优雅、简便的解决你的问题。每一个解决方案都不可能解决所有问题,你应该去掌握尽可能多的不同解决方案。
Vue使用render函数(以js文件的形式生成组件)
loading.js
export default {
//组件名
name: "strReverse",
//属性
props: {
msg: {
type: String,
default: "",
},
},
data:()=>{
return {
message:1
}
},
//方法
methods: {
reversedMessage() {
return this.msg.split("").reverse().join("");
},
add(){
this.message++
}
},
//生成html
render(h) {
return (<div>
{
this.message}
<button onClick={
() => this.add(this)}>message++</button>
</div>)
},
};
Vue模版实例作为组件注册使用
loading.vue
<template>
<div class="contain">
<h1>Load....</h1>
<button @click="count++">{
{count}}++</button>
</div>
</template>
<script>
export default {
data(){
return {
count:1
}
}
}
</script>
<styl lang='less' scoped>
.contain{
border: 1px solid rebeccapurple;
width: 200px;
margin: 0 auto;
}
</styl>
在main.js注册
import Loading from '@/components/global/Loading.js'
import Load from '@/components/global/Load.vue'
Vue.component('Loading',Loading);
Vue.component('Load',Load);