首頁> web前端> Vue.js> 主體

如何在Vue3中使用JSX?

WBOY
發布: 2023-05-09 21:09:19
轉載
2129 人瀏覽過

    1. Vue3 中JSX 的基本應用

    • 使用.jsx 格式檔案與defineComponent

    • defineComponent 可傳入setup 函數或元件的設定

    • 插值使用單括號{}

    #1.1 在.vue 檔案中使用jsx

    // 父   // JSXDemo1.vue 
    登入後複製

    1.2 .jsx檔案格式

    // 父组件 import { defineComponent, ref } from 'vue' import JSXChild from './JSXChild.jsx' export default defineComponent(() => { // 传入 setup 函数 const countRef = ref(300) const render = () => { return <> 

    DEMO2--{countRef.value}

    } return render }) // 子组件 JSXChild.jsx import { defineComponent } from 'vue' export default defineComponent({ // 传入组件配置 props: ['a'], setup (props) { const render = () => { return <>

    child {props.a}

    } return render } })
    登入後複製

    2. JSX 和template 的差異

    • 語法上有很大差異

    • #JSX 本質上是js 程式碼,可以使用js 的任何能力

    • template 只能嵌入簡單的js 表達式,其他需要指令,如v-if

    • JSX 已成為ES 規範,template 還是Vue 自家規範

    • 本質是相同的:

    • #都會被編譯成js 程式碼(render 函數)

    2.1 插值

    • #template 使用雙括號{{ }}

    • ##jsx 使用單括號{ }

    // template  // jsx const render = () => { return <> 

    child {props.a}

    }
    登入後複製
    2.2 自訂元件

    • template 元件名稱使用時可改變大小寫或是駝峰,jsx 不可更改

    • 引入動態參數,template使用冒號參數名稱(:msg='msg'),jsx 不需要冒號

    #
    // template   // jsx 组件名称不可变,要和引入名字保持一致 import { defineComponent, ref } from 'vue' import JSXChild from './JSXChild.jsx' export default defineComponent(() => { const countRef = ref(300) const render = () => { return <> 

    DEMO2--{countRef.value}

    } return render })
    登入後複製
    2.3 屬性和事件

    template 區分屬性和事件的寫法,jsx 不區分
    // jsx 属性和事件的写法一样 import { defineComponent, ref } from 'vue' import JSXChild from './JSXChild.jsx' export default defineComponent(() => { const countRef = ref(300) function onChange () { console.log('onChange') } const render = () => { return <> 

    DEMO2--{countRef.value}

    } return render })
    登入後複製
    2.4 條件和循環

    #條件template 使用v-if 指令,jsx 在表達式中使用&& (類似if( a && b))
    // template v-if   // jsx &&符号判断 import { defineComponent, ref } from 'vue' import JSXChild from './JSXChild.jsx' export default defineComponent(() => { const flagRef = ref(true) function changeFlagRef () { flagRef.value = !flagRef.value } const render = () => { return <> 

    DEMO2--{flagRef.value.toString()}

    {flagRef.value && } } return render })
    登入後複製
    循環template 使用v-for 指令,jsx 使用陣列的.map 函數
    // template v-for   // jsx 数组 .map 函数 import { defineComponent, reactive } from 'vue' export default defineComponent(() => { const state = reactive({ list: ['a1', 'b1', 'c1'] }) const render = () => { return <> 
      {state.list.map(item =>
    • {item}
    • )}
    } return render })
    登入後複製
    3. JSX 和slot (體會JSX 的優越性)

    • slot 是Vue 發明的概念,為了完善template 的能力

    • slot 一直是Vue 初學者的“噩夢”,特別是:作用域slot

    • 但使用JSX 將很容易理解,因為JSX 本質就是js

    以上是如何在Vue3中使用JSX?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    相關標籤:
    來源:yisu.com
    本網站聲明
    本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn