W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
就變化而言,屬于高等級(jí)內(nèi)容:
props
和 context
的普通函數(shù)創(chuàng)建 (即:slots
,attrs
,emit
)。functional
attribute 在單文件組件 (SFC) <template>
已被移除{ functional: true }
選項(xiàng)在通過(guò)函數(shù)創(chuàng)建組件已被移除更多信息,請(qǐng)繼續(xù)閱讀!
在 Vue 2 中,函數(shù)式組件有兩個(gè)主要用例:
然而,在 Vue 3 中,有狀態(tài)組件的性能已經(jīng)提高到可以忽略不計(jì)的程度。此外,有狀態(tài)組件現(xiàn)在還包括返回多個(gè)根節(jié)點(diǎn)的能力。
因此,函數(shù)式組件剩下的唯一用例就是簡(jiǎn)單組件,比如創(chuàng)建動(dòng)態(tài)標(biāo)題的組件。否則,建議你像平常一樣使用有狀態(tài)組件。
使用 <dynamic-heading>
組件,負(fù)責(zé)提供適當(dāng)?shù)臉?biāo)題 (即:h1
,h2
,h3
,等等),在 2.x 中,這可能是作為單個(gè)文件組件編寫(xiě)的:
// Vue 2 函數(shù)式組件示例
export default {
functional: true,
props: ['level'],
render(h, { props, data, children }) {
return h(`h${props.level}`, data, children)
}
}
或者,對(duì)于喜歡在單個(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>
現(xiàn)在在 Vue 3 中,所有的函數(shù)式組件都是用普通函數(shù)創(chuàng)建的,換句話說(shuō),不需要定義 { functional: true }
組件選項(xiàng)。
他們將接收兩個(gè)參數(shù):props
和 context
。context
參數(shù)是一個(gè)對(duì)象,包含組件的 attrs
,slots
,和 emit
property。
此外,現(xiàn)在不是在 render
函數(shù)中隱式提供 h
,而是全局導(dǎo)入 h
。
使用前面提到的 <dynamic-heading>
組件的示例,下面是它現(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
在 3.x 中,有狀態(tài)組件和函數(shù)式組件之間的性能差異已經(jīng)大大減少,并且在大多數(shù)用例中是微不足道的。因此,在 SFCs 上使用 functional
的開(kāi)發(fā)人員的遷移路徑是刪除該 attribute,并將 props
的所有引用重命名為 $props
,將 attrs
重命名為 $attrs
。
使用之前的 <dynamic-heading>
示例,下面是它現(xiàn)在的樣子。
<template>
<component
v-bind:is="`h${$props.level}`"
v-bind="$attrs"
/>
</template>
<script>
export default {
props: ['level']
}
</script>
主要的區(qū)別在于:
functional
attribute 在 <template>
中移除listeners
現(xiàn)在作為 $attrs
的一部分傳遞,可以將其刪除有關(guān)新函數(shù)式組件的用法和對(duì)渲染函數(shù)的更改的詳細(xì)信息,見(jiàn):
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: