jsx学习

https://vue-jsx-explorer.netlify.app/#const%20App%20%3D%20()%20%3D%3E%20%3Cdiv%3EHello%20World%3C%2Fdiv%3E%20%3D%3E%20%3Cdiv%3EHello%20World%3C%2Fdiv%3E)
image.png

配置

  1. yarn add @vitejs/plugin-vue-jsx
  1. import vueJsx from '@vitejs/plugin-vue-jsx'
  2. export default defineConfig({
  3. plugins: [ vueJsx()]
  4. })
  1. {
  2. // include 需要包含tsx
  3. "include": ["src/*", "src/**/*.vue", "src/**/*.tsx", "src/**/*.jsx", "src/**/*.ts", "src/**/*.js"],
  4. "compilerOptions": {
  5. // 在.tsx文件里支持JSX
  6. "jsx": "preserve",
  7. }
  8. }

使用

  1. export default definedComponents({
  2. setup(props){
  3. return ()=>(
  4. <div>
  5. Hello,World
  6. </div>
  7. )
  8. }
  9. })
  1. <script lang='tsx'>
  2. import {definedComponents} from 'vue'
  3. export default definedComponents({
  4. setup(props){
  5. return ()=>(
  6. <div>
  7. Hello,World
  8. </div>
  9. )
  10. }
  11. })
  12. </script>

jsx中 使用 transition

  1. import {Transition,ref} from 'vue'
  2. export default definedComponents({
  3. setup(props){
  4. // 只有点击时执行
  5. const a = ref(false)
  6. return ()=>(
  7. <>
  8. <Transition>
  9. <div v-show={a}></div>
  10. </Transition>
  11. )
  12. }
  13. })
  1. // jsx/tsx中循环出来的标签元素上有点击事件的话 会自动调用事件
  2. // 例如
  3. export default definedComponents({
  4. setup(props){
  5. // 只有点击时执行
  6. const click = (e,val)=>{
  7. consloe.log(e,val)
  8. }
  9. return ()=>(
  10. <>
  11. {[1,2,3].map((item,index)=>{
  12. return (
  13. <div onClick={(e)=>{click(e,'112')}}><>
  14. )
  15. })}
  16. </>
  17. )
  18. }
  19. })

Demo

  1. <script lang="ts">
  2. import { defineComponent } from 'vue'
  3. export default defineComponent({
  4. data() {
  5. return {
  6. count: 1
  7. }
  8. }
  9. })
  10. </script>
  11. <template>
  12. <!-- type checking and auto-completion enabled -->
  13. {{ count.toFixed(2) }}
  14. </template>

Setup

  1. <script setup lang="ts">
  2. // TypeScript enabled
  3. import { ref } from 'vue'
  4. const count = ref(1)
  5. </script>
  6. <template>
  7. <!-- type checking and auto-completion enabled -->
  8. {{ count.toFixed(2) }}
  9. </template>