Vite + Vue3 使用TSX/JSX

6,479 阅读1分钟

安装

yarn add @vitejs/plugin-vue-jsx

or

npm install @vitejs/plugin-vue-jsx -D

配置

vite.config.ts 文件中挂载

import vueJsx from '@vitejs/plugin-vue-jsx'
export default defineConfig({
 plugins: [ vueJsx()]
})

tsconfig.json 文件中

{
  // include 需要包含tsx
"include": ["src/*", "src/**/*.vue", "src/**/*.tsx", "src/**/*.jsx", "src/**/*.ts", "src/**/*.js"],
 "compilerOptions": {
    // 在.tsx文件里支持JSX
    "jsx": "preserve",
 }
}

使用

新建**.tsx

// index.tsx
export default definedComponents({
  setup(props){
    return ()=>(
      <div>
      Hello,World
      </div>
    )
  }
})

新建**.vue

不需要templatescript上加lang='tsx'

// index.vue
<script lang='tsx'>
import {definedComponents} from 'vue'
export default definedComponents({
  setup(props){
    return ()=>(
      <div>
      Hello,World
      </div>
    )
  }
})
</script>

文档

jsx语法Seegithub.com/vuejs/jsx-n…

探坑

jsx/tsx中循环出来的标签元素上有点击事件的话 会自动调用事件

// 例如
export default definedComponents({
  import {definedComponents} from 'vue'
  setup(props){
    // 会被调用3次
    const click = (val)=>{
      consloe.log(val)
      // 112
      // 112
      // 112
    }
    return ()=>(
      <>
      {[1,2,3].map((item,index)=>{
        return (
          // 而且 这样写拿不到原生事件 event
          <div onClick={click('112')}><>
        )
      })}
      </>
    )
  }
})

正确应该是onClick={(e)=>{click(e,'112')}}这样也可以拿到原生事件

// jsx/tsx中循环出来的标签元素上有点击事件的话 会自动调用事件
// 例如
export default definedComponents({
  setup(props){
    // 只有点击时执行
    const click = (e,val)=>{
      consloe.log(e,val)
    }
    return ()=>(
      <>
      {[1,2,3].map((item,index)=>{
        return (
          <div onClick={(e)=>{click(e,'112')}}><>
        )
      })}
      </>
    )
  }
})

jsx中 使用 transition

import {Transition,ref} from 'vue'
export default definedComponents({
  setup(props){
    // 只有点击时执行
    const a = ref(false)
    return ()=>(
      <>
        <Transition>
        <div v-show={a}></div>
      </Transition>
    )
  }
})