Vue3使用TSX

Vue 使用Tsx

准备工作

  1. 安装 vue3 的 typescript 版本

    yarn create @vitejs/app
  2. 安装 @vitejs/plugin-vue-jsx

    yarn add -D @vitejs/plugin-vue-jsx
  3. 配置 vite.coonfig.ts

       import { defineConfig } from 'vite';
       import vue from '@vitejs/plugin-vue';
       import vueJsx from '@vitejs/plugin-vue-jsx';
       
       export default defineConfig({
         plugins: [vue(), vueJsx({})],
       });
    
    4. 配置tsconfig.json
    
       ```json
       {
         "compilerOptions": {
           "jsx": "preserve",
           "jsxFactory": "h",
           "jsxFragmentFactory": "Fragment",
         }
       }

Tsx的使用

  • 新建.tsx后缀的文件

  • 在.vue中引入 import renderDom from "./App";

  • 不支持 v-if v-bind v-on v-for

  • 具体用法

    import { ref } from "vue"
    let v = ref<string>("123")
    let flag = true
    let Arr = [1, 2, 3, 4, 5]
    type Props = {
        name: string
    }
    const renderDom = (props: Props, ctx: any) => {
        return (
            <div>
                <h1>{props.name}</h1>
                <input v-model={v.value} type="text" />
                <div onClick={clickTap.bind(this, ctx)}>Hello Tsx {v.value}</div>
                <div v-show={flag}>Hello Tsx {v.value}</div>
                {
                    flag && <div>flag is true</div>
                }
                {
                    !flag && <div>flag is false</div>
                }
                {
                    Arr.map((item, index) => {
                        return <div onClick={() => { alert(index) }} key={index}>{item} - {index}</div>
                    })
                }
            </div>
        )
    }
    
    const clickTap = (ctx: any) => {
        ctx.emit("clickTap","123")
    }
    
    export default renderDom