在Vue2.X中,函數(shù)式組件有兩個(gè)主要應(yīng)用場景:作為性能優(yōu)化,因?yàn)樗鼈兊某跏蓟俣缺扔袪顟B(tài)組件快得多;返回多個(gè)根節(jié)點(diǎn)。
然而在Vue3.X中,有狀態(tài)組件的性能已經(jīng)提高到可以忽略不計(jì)的程度。此外,有狀態(tài)組件現(xiàn)在還包括返回多個(gè)根節(jié)點(diǎn)的能力。
因此,函數(shù)式組件剩下的唯一應(yīng)用場景就是簡單組件,比如創(chuàng)建動(dòng)態(tài)標(biāo)題的組件。否則,建議你像平常一樣使用有狀態(tài)組件。
2.x語法:
使用<dynamic-heading>組件,負(fù)責(zé)提供適當(dāng)?shù)臉?biāo)題,例如H1,H2
,H3等等,在2.X中,這可能是作為單個(gè)文件組件編寫的:
// Vue 2 函數(shù)式組件示例
export default {
functional: true,
props: ['level'],
render(h, { props, data, children }) {
return h(`h${props.level}`, data, children)
}
}
或者,對于喜歡在單個(gè)文件組件中使用<template>的用戶:
<!-- Vue 2 函數(shù)式組件示例使用 <template> -->
<template functional>
<component
:is="`h${props.level}`"
v-bind="attrs"
v-on="listeners"
/>
</template>
<script>
export default {
props: ['level']
}
</script>
3.X語法:
通過函數(shù)創(chuàng)建組件
現(xiàn)在在Vue3中,所有函數(shù)式組件都是普通函數(shù)創(chuàng)建的,換句話說,不需要定義{functional: true}組件選項(xiàng)。
它們將接收兩個(gè)參數(shù):props和context。
context:是一個(gè)對象,包含組件attrs,slots和emit property。
此外,現(xiàn)在不是在render函數(shù)中隱式提供h,而是全局導(dǎo)入h。
前面提到的組件實(shí)例,現(xiàn)在改為:
import { h } from 'vue'
const DynamicHeading = (props, context) => {
return h(`h${props.level}`, context.attrs, context.slots)
}
DynamicHeading.props = ['level']
export default DynamicHeading
單文件組件 SFC
在3.x中,有狀態(tài)組件和函數(shù)式組件之間的性能差異已經(jīng)大大減少,并且在大多數(shù)用例中是微不足道的。因此,在SFC上使用functional的開發(fā)人員的遷移路徑是刪除改attrbute,并將props的所有引用重命名為$props,將attrs重命名為$attrs。
使用之前的實(shí)例,下面是現(xiàn)在這個(gè)樣子:
<template>
<component
v-bind:is="`h${$props.level}`"
v-bind="$attrs"
/>
</template>
<script>
export default {
props: ['level']
}
</script>
主要的區(qū)別就在于:
1. functional attribute 在<template>中移除
2.listeners現(xiàn)在作為$attrs的一部分傳遞,可以將其刪除