Vue3 + TSX中 插槽用法

2,284 阅读1分钟

一、背景

最近在做 vue3+TSX 的项目,使用插槽来封装基本布局组件,特记录下 tsx 中插槽的用法。

二、代码示例

BaseLayout.tsx组件

import { defineComponent, FunctionalComponent } from "vue";
import s from "./BaseLayout.module.scss";

export const WelcomeLayout: FunctionalComponent = (props, { slots }) => (
  <div class={s.wrapper}>
    <div class={s.card}>
      {slots.imgs?.()}
      {slots.title?.()}
    </div>
    <div class={s.describe}>{slots.des?.()}</div>
  </div>
);

PageOne.tsx组件

import { defineComponent } from "vue";
import s from "./BaseLayout.module.scss";
import pig from "../../../assets/pig.svg";
import { BaseLayout } from "./BaseLayout";

export const PageOne = {
  setup() {
    return () => (
      <BaseLayout>
        {{
          imgs: () => <img src={pig} class={s.icon} />,
          title: () => <h2> title </h2>,
          des: () => <>
                  <p> 描述信息1。。。。。</p>
                  <p> 描述信息2。。。。。</p>
              </>
        }}
      </BaseLayout>
    );
  },
};

三、总结

仅记录下所用写法,更多写法可参考 vuejs/babel-plugin-jsx: JSX for Vue 3 (github.com)