vue3使用@vitejs/plugin-vue-jsx来满足jsx
jsx在vue3的使用语法
jsx在vue2种使用
1、安装插件@vitejs/plugin-vue-jsx
npm install --save-dev @vitejs/plugin-vue-jsx
复制
2、在 vite.config.js 中添加插件
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' export default defineConfig({ plugins: [ vue(), vueJsx() ] })
复制
3、使用jsx(注意jsx和template只能渲染一个): script的lang设置为jsx
以下是三种使用方式:
3.1父子组件,子组件使用jsx,在父组件template模板里渲染
-------------------------------以下是父组件代码far.vue----------------- <template> <div class="home"> <div>父组件div</div> <div> 子组件内容: <JSXDemo1 /> </div> </div> </template> <script> import JSXDemo1 from './son.vue' export default { name: 'HomeView', components: { JSXDemo1 } } </script> ----------------以下是子组件son.vue使用jsx-------------------- <script lang="jsx"> import { ref } from 'vue' export default { setup () { const countRef = ref(200) const render = () => { return <span>JSX--{countRef.value}</span> // jsx就是js语法,所以要加 .value } return render } } </script>
复制
3.2推荐return写法
<script lang="jsx"> // 导入所需的 Vue 3 API 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 = '默认值') => { console.log(msg); console.log(props); } return () => ( <div> <div class='async'>{str.value}</div> <button onClick={clickFunc1}>不传参数点击</button> <button onClick={() => clickFunc2('额外参数')}>传参数点击</button> </div> ); } }) </script> <!-- 在此处添加样式 -->
复制
3.3通过render写jsx
<script lang="jsx"> import { defineComponent, ref, createVNode, render } from 'vue'; export default defineComponent({ setup() { let num = ref(13) const jsxContent = ( <div> <h1>Hello, JSX!</h1> <p id={num.value}>This is a JSX variable.{num.value}</p> </div> ); const jsxVariable = ref(jsxContent); return { jsxVariable, }; }, render() { return ( <div> <h2>JSX使用</h2> {this.jsxVariable} </div> ); }, }); </script> <!-- 在此处添加样式 -->
复制
4.对比jsx和template是使用区别