render函数
一、什么是render函数
render是一个模板渲染函数。
template模板里面的HTML语法,组建页面时在底层会被编译,在Vue中会生成(解析成)render函数,因为Vue中采用的是虚拟DOM所以拿到template 模板时要转译成虚拟节点函数。Render函数会调用h方法,返回一个内容,内容是Vue中的一个虚拟DOM,这个虚拟DOM就是真实DOM节点的js对象表述。
二、Render函数的用法
我们使用template模板写的内容如下:
<script>
const ateApp({
template:`<div class="area">hello</div>`
});
const unt("#root")
</script>
如果使用render函数来写是怎样的呢?
<script>
const ateApp({
render(){
const{h}=Vue;
return h("div",{class:"area"},["hello"])
}
});
const unt("#root")
</script>
使用render函数生成的DOM结构在控制台显示如下,可以看出和通过template实现的DOM结构是一样的。
render函数生成的虚拟DOM节点的语法如下:
render(){
const{h}=Vue;
return h(元素名,{元素属性},元素内容)
script在html中的用法
}
其中,h函数中包含三个参数:
第一个参数是标签名称,类型必须是String
第二个参数是标签的属性内容,类型必须是Object
第三个参数是子级虚节点内容,类型可以是字符串或者数组。这个参数如果是数组类型,则可以实现DOM结构的子节点嵌套,代码如下:
<body>
<div id="root"></div>
</body>
<script>
const ateApp({
data(){
return{
content:"目录",
list:["css","js","html"]
}
},
template:`
<test:list="list">{{content}}</test>`
});
appponent("test",{
props:["list"],
render(){
const{h}=Vue;
return h("div",{style:"color:blue"},
["",h("div",{},this.$slots.default()),h("ul",{},
["",h("li",{},this.list[2]),h("li",{},this.list[0]),h("li",{},th is.list[1])]
)])
}
})
const unt("#root")
</script>
在控制台显示的DOM结构如下:
在子组件中使用render函数来实现DOM结构,通过插槽来实现父组件对子结构内容的自定义,并且将父组件中传递来的数据使用在h函数的参数中,如下代码,实现的功能是点击按钮,页面的hello文本变为bye,且文字颜从粉变为红,代码如下:
<body>
<div id="root"></div>
</body>
<script>
const ateApp({
data(){
return{
content:"hello",
mycolor:"pink"
}
},
methods:{
handleClick(){
t==="hello"){
}else{
}
}
},
/*调用子组件,并给子组件传递参数mycolor*/
template:`
<test:mycolor="mycolor">{{content}}</test>
<button@click="handleClick">点击</button>`
});
appponent("test",{
props:["mycolor"],/*子组件接收参数mycolor*/
render(){
const{h}=Vue;
/*子组件中在h的第二个参数-属性里使用接受的动态参数mycolor*/
return
h("div",{style:"color:"+lor},this.$slots.default()) }
})
const unt("#root")
</script>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。