Vue3 在 render 函数中使用 slot

工作上有一个需求:需要为一个按钮添加文本提示,我使用的是 Tooltip 组件,不过这个模块需要使用 render 函数编写,所以需要在 render 函数中使用到 slot

在网上查到的资料大部分都不太可行或代码过于臃肿,最后在官方文档找到了解决方案

自定义插槽

自己编写组件时使用 slot

默认插槽

render 函数渲染后等价于下面的 html

render

1
h('div', slots.default())

html

1
2
3
<div>
<slot />
</div>

单个具名插槽

render 函数渲染后等价于下面的 html

render

1
2
3
h('div', slots.header(
{title: props.headerTitle}
))

html

1
2
3
<div>
<slot name="header" :title="props.headerTitle"/>
</div>

多个具名插槽

render 函数渲染后等价于下面的 html

render

1
2
3
4
5
6
7
8
h('div', null, [
h('div', slots.header(
{title: props.headerTitle}
)),
h('div', slots.default()),
h('div', slots.footer()),
])

html

1
2
3
4
5
<div>
<slot name="header" :title="props.headerTitle"/>
<slot />
<slot name="footer" />
</div>

传递插槽

使用组件时,设置组件的插槽内容

单个默认插槽

1
h(MyComponent, null, () => 'hello world')

具名插槽

1
2
3
4
5
6
7
8
9
10
11
h(Ntooltip, null, {
trigger: () => h(NButton, {
style:{
display: custom && custom.show ? 'inline-flex' : 'none'
},
type: 'primary',
...custom,
onClick: () => onCustom()
}, () => custom ? custom.value : '自定义'),
default: () => h('span', null, custom.tooltip)
})