跳至主要內容

Vue3 在 render 函数中使用 slot

望间代码VueVue3大约 1 分钟

Vue3 在 render 函数中使用 slot

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

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

自定义插槽

自己编写组件时使用 slot

默认插槽

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

render

h("div", slots.default());

html

<div>
  <slot />
</div>

单个具名插槽

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

render

h("div", slots.header({ title: props.headerTitle }));

html

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

多个具名插槽

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

render

h("div", null, [
  h("div", slots.header({ title: props.headerTitle })),
  h("div", slots.default()),
  h("div", slots.footer()),
]);

html

<div>
  <slot name="header" :title="props.headerTitle" />
  <slot />
  <slot name="footer" />
</div>

传递插槽

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

单个默认插槽

h(MyComponent, null, () => "hello world");

具名插槽

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),
});
上次编辑于:
贡献者: ViewRoom