11. jsx在vue3中的基本使用

2023-10-08 22:20:49发布
57

1、安装jsx插件

npm i @vitejs/plugin-vue-jsx


2、在vite.config.js中配置


3、定义一个jsx的文件,如test.jsx,然后编写以下代码

import { defineComponent, reactive, ref } from "vue";
import './test.scss' // 引用外部样式

// 使用defineComponent定义jsx
export default defineComponent(()=> {
    
    // 定义变量
    const num = ref(0);
    const val = ref('')
    const tableData = reactive([{
        name: 'tom',
        age: 12
    },{
        name: 'marry',
        age: 14
    }])

    // 定义函数
    const add = ()=> {
        num.value++
    }

    /**
     * render函数代替vue的template
     * 有以下几点是需要注意的
     * 1、return后面带的是<>代码....</>
     * 2、注意使用变量用的是{ } 而不是 {{}}
     * 3、点击事件不能用@click,而是用原生的onClick
     * 4、for循环不能用v-for,而是用map代替
     * 5、v-model是可以继续使用的
     */
    const render = ()=> {
        return <>
            <div>
                <h2 class="title">数字相加案例</h2>
                <div>{ num.value }</div>
                <el-button onClick={()=> add()}>add</el-button>
            </div>
            <div>
                <h2 class="title">双向数据绑定案例</h2>
                <el-input v-model={val.value}></el-input>
                { val.value }   
            </div>
            <div>
                <h2 class="title">循环案例</h2>
                <ul>
                    {
                        tableData.map(item => {
                            return <li>{item.name} {item.age}</li>
                        })
                    }
                </ul>
            </div>
        </>
    }

    return render
})


4、在别的页面使用

<template>
  <div>
    <test></test>
  </div>
</template>
<script setup>
  import test  from './test'
</script>