vue3+vite使用jsx和tsx详情

安装@vitejs/plugin-vue-jsx

yarn add -D @vitejs/plugin-vue-jsx
npm i -D @vitejs/plugin-vue-jsx

配置vite.config.js

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

使用实战

新建xxx.tsx或者xxx.jsx,注意不再是vue为后缀

第一种写法使用this

使用了this,个人不太推荐

import { defineComponent, ref } from 'vue';
export default defineComponent({
  setup(){
    const str = ref('tsx的使用');
    const clickFunc1 = () => {
      console.log('没有参数');
    }
    const clickFunc2 = (msg: string = '默认值') => {
      console.log(msg);
    }
    return {
      str,
      clickFunc1,
      clickFunc2
    };
  },
  render(){
    return (
      <>
        
{this.str}
                          );   } })

第二种写法

函数体等价于setup,此方式无法获取到props与emits等等(可能我没有了解到),存在交互性强的也不建议使用,否则可以考虑

import { defineComponent, ref } from 'vue';
export default defineComponent(() => {
  const str = ref('tsx的使用');
  const clickFunc1 = () => {
    console.log('没有参数');
  }
  const clickFunc2 = (msg: string = '默认值') => {
    console.log(msg);
  }
  const render = (
    <>
      
{str.value}
                  );   return () => render; })

第三种写法

比较推荐这种写法

import { defineComponent, ref } from 'vue';
export default defineComponent({
  props: {
    params: {
      type: Object,
      default: () => {}
    }
  },
  setup(props){
    const str = ref('tsx的使用');
    const clickFunc1 = () => {
      console.log('没有参数');
    }
    const clickFunc2 = (msg: string = '默认值') => {
      console.log(msg);
      console.log(props);
    }
    return () => (
      <>
        
{str.value}
                          );   } })

到此这篇关于vue3+vite使用jsx和tsx详情的文章就介绍到这了,更多相关vue3 jsx/tsx内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(vue3+vite使用jsx和tsx详情)