经验分享
Vue3 & vite封装一个tsx组件
第一次使用vue3+ts封装tsx组件,后续将不断探索更高级的用法...
2024-05-15 06:19:26
21

安装依赖

npm install @vitejs/plugin-vue-jsx --save-dev

配置tsconfig.json

{
  "compilerOptions":{
    "jsx": "preserve",
    "jsxFactory": "h",
    "jsxFragmentFactory": "Fragment"
  }
}

配置vite.config.ts

import vueJsx from "@vitejs/plugin-vue-jsx";

export default () => defineConfig({
  plugins:[
    // ...
    vueJsx()
  ]
})

简单封装一个组件

// components/demo/index.tsx
import { defineComponent } from "vue";
import { Button as AButton } from "ant-design-vue";

export default defineComponent({
  // 父给子传参
  props:{
    name:{ type:String, default:"" }
  },
  // 子给父抛事件
  emits:["clk"],
  setup(props, { emit }){
    // 拿到父给子传的值
    console.log(props.name)

    // 子给父抛事件传参
    const onClick = () => emit("clk");

    // 渲染组件
    return () => (
      <div>
        <AButton type="primary" onClick={onClick}>点击这里</AButton>
      </div>
    )
  }
})

简单使用

<script setup lang="ts">
import Demo from "@/components/demo";
const onClk = () => {
  console.log(222)
}
</script>

<template>
  <Demo  name="111" @clk="onClk" />
</template>

<style lang="less" scoped></style>