使用.jsx 格式檔案與defineComponent
defineComponent 可傳入setup 函數或元件的設定
插值使用單括號{}
// 父// JSXDemo1.vue
// 父组件 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 } })
語法上有很大差異:
#JSX 本質上是js 程式碼,可以使用js 的任何能力
template 只能嵌入簡單的js 表達式,其他需要指令,如v-if
JSX 已成為ES 規範,template 還是Vue 自家規範
本質是相同的:
#都會被編譯成js 程式碼(render 函數)
2.2 自訂元件
#template 使用雙括號{{ }}
- ##jsx 使用單括號{ }
// template{{ name }} -- {{ age }}
// jsx const render = () => { return <>child {props.a}
> }登入後複製
2.3 屬性和事件 template 區分屬性和事件的寫法,jsx 不區分#
- 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.4 條件和循環 #條件template 使用v-if 指令,jsx 在表達式中使用&& (類似if( a && b))// 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 }) 登入後複製
循環template 使用v-for 指令,jsx 使用陣列的.map 函數// template v-iftemplate demo
// 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 }) 登入後複製
3. JSX 和slot (體會JSX 的優越性)// template v-for// jsx 数组 .map 函数 import { defineComponent, reactive } from 'vue' export default defineComponent(() => { const state = reactive({ list: ['a1', 'b1', 'c1'] }) const render = () => { return <>
- {{ item }}
{state.list.map(item =>
> } return render })- {item}
)}登入後複製
- slot 是Vue 發明的概念,為了完善template 的能力
- slot 一直是Vue 初學者的“噩夢”,特別是:作用域slot
- 但使用JSX 將很容易理解,因為JSX 本質就是js
以上是如何在Vue3中使用JSX?的詳細內容。更多資訊請關注PHP中文網其他相關文章!