渲染函数
h() 函数
官网介绍
参数介绍: h(参数1,参数2, 参数3)
- 参数1:必须要有
可以是一个标签的字符串,如: 'div‘
也可以是个组件:如:MyComponent
也可以个对象或者函数,总之第一个参数就是我们要渲染内容的一个容器(标签)import MyComponent from './MyComponent.vue' h(MyComponent)
- 参数2:可选
props,attribute,事件等
就是参数1的一些属性,css样式,事件等// CSS h('div', {class: 'title'}) // 事件 h('div', {onClick: () => {console.log('点击事件')}}) // 组件传值 import MyComponent from './MyComponent.vue' h(MyComponent, {msg: '传值'} )
- 参数3:可选
可以是文本内容
可以是一个有h()组成的数组,如实现标签的嵌套h('div', {class: 'title'}, '展示的文本')
可以是插槽对象<div> <p></p> </div> h('div' null, [ h('p') ])
import MyComponent from './MyComponent.vue' // 默认插槽 h(MyComponent, {msg: '传值'}, { default: () => { return h('div', null, '插槽默认信息') } )
vue2.x 示例代码
App.vue
<script>
export default {
render (h) {
return h('div', {class: 'my-app'}, '我是app')
}
};
</script>
<style >
.my-app {
color: blue;
}
</style>
实现官方的示例代码
vue3.x
App.vue
<script>
import { h } from 'vue'
import MyComponent from './MyComponent.vue'
export default {
// 使用render
render () {
// 根标签 div
return h('div',{class: 'my-app'},[
// 标题展示
h('h1', {class: 'app-h1'}, '我是App根组件'),
// 组件展示
h(MyComponent, {level: 1}, '一级标题'),
h(MyComponent, {level: 2}, {
default: () => {
return h('p', null, '我是插槽,二级标题')
}
})
])
}
}
</script>
<style scoped>
.my-app {
color: skyblue;
}
.app-h1 {
color: #333;
}
</style>
MyComponent
<script>
import { h } from 'vue'
export default {
props: {
level: {
type: Number,
required: true
}
},
// 使用setup
setup (props, {slots}) {
console.log(slots)
return () => {
return h(
'h' + props.level, // 标签 参数1
{ onClick: () => { // 点击事件 参数2
console.log('点击了 h' + props.level + '标签')
}},
// 插槽 参数3
slots.default()
)
}
}
}
</script>
<style scoped>
</style>