TSX

用过react的肯定了解jsx语法,白话说就是,在js语法中也可以使用html。 而vue3对typeScript支持度提高,也可以试试TSX。

安装

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

配置

vite.config.ts 配置文件

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

tsconfig.json 配置文件

    "jsx": "preserve",
    "jsxFactory": "h",
    "jsxFragmentFactory": "Fragment",

使用

在目录新建tsx文件

TIPS:

  1. tsx不会自动解包使用ref加.vlaue ! ! !
  2. v-show v-model v-bind 可正常使用
  3. v-if v-for用不了,可用三元表达式 map替代
  4. v-on 事件得和react一样,on开头,事件首字母大写,如"onClick"
import { ref } from 'vue'
 
let v = ref<string>('')
 
const renderDom = () => {
    return (
        <>
           <input v-model={v.value} type="text" />
           <div>
               {v.value}
           </div>
        </>
    )
}
 
export default renderDom

props 接受值

import { ref } from 'vue'
 
type Props = {
    title:string
}
 
const renderDom = (props:Props) => {
    return (
        <>
            <div>{props.title}</div>
            <button onClick={clickTap}>点击</button>
        </>
    )
}
 
const clickTap = () => {
    console.log('click');
}
 
export default renderDom

emit派发

type Props = {
    title: string
}
 
const renderDom = (props: Props,content:any) => {
    return (
        <>
            <div>{props.title}</div>
            <button onClick={clickTap.bind(this,content)}>点击</button>
            <button onClick={() => clickTap(content)}>点击</button>
        </>
    )
}
 
const clickTap = (ctx:any) => {
 
    ctx.emit('on-click',1)
}

slot插槽

const A = (props, { slots }) => (
  <>
    <h1>{ slots.default ? slots.default() : 'foo' }</h1>
    <h2>{ slots.bar?.() }</h2>
  </>
);
 
const App = {
  setup() {
    const slots = {
      bar: () => <span>B</span>,
    };
    return () => (
      <A v-slots={slots}>
        <div>A</div>
      </A>
    );
  },
};
 
// or
 
const App = {
  setup() {
    const slots = {
      default: () => <div>A</div>,
      bar: () => <span>B</span>,
    };
    return () => <A v-slots={slots} />;
  },
};
 
// or you can use object slots when `enableObjectSlots` is not false.
const App = {
  setup() {
    return () => (
      <>
        <A>
          {{
            default: () => <div>A</div>,
            bar: () => <span>B</span>,
          }}
        </A>
        <B>{() => "foo"}</B>
      </>
    );
  },
};
Last Updated:
Contributors: haizhiguang