使用
安装
| yarn add @vitejs/plugin-vue-jsx |
配置 vite.config.ts
| import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' // https://vitejs.dev/config/ export default defineConfig({ plugins: [vue(),vueJsx()], }) |
使用 tsx 组件
| <template> <ComC></ComC> </template> <script setup lang="ts"> import ComC from "./components/comC.tsx" </script> |
tsx 写法
创建 comC.tsx 组件
函数式写法
| export default function(){ return (<div>this is tsx Component</div>) } |
option 方式
| import { defineComponent } from "vue"; export default defineComponent({ data(){ return { name:"tsx option" } }, render(){ return (<div>{this.name}</div>) } }) |
setup 方式
| import { defineComponent } from "vue"; export default defineComponent({ setup(){ return ()=>(<div>this setup</div>) } }) |
setup 指令注意事项
- 使用单花括号代替双花括号
- 不会自动解包 {xxx.value}
- 不支持 v-if 指令,使用三目运算符替代
- 使用 map 替代 v-for , 用法同 react 相似
- 使用单花括号替代 v-bind, 用法同 react
- 使用 props /emit 接收传值
props
| type Props = { title:string } export default function (props:Props){ console.log(props.title); return (<div>{props.title}</div>) } |
emit
| export default function (props,ctx:any){ const handleClick = (ctx:any)=>{ ctx.emit("on-click","传值") } return ( <div> <button onClick={()=>handleClick(ctx)}>click</button> </div> ) } |