Vue 3.0 函數(shù)式組件

2021-07-16 11:45 更新

#概覽

就變化而言,屬于高等級(jí)內(nèi)容:

  • 在 3.x 中,函數(shù)式組件 2.x 的性能提升可以忽略不計(jì),因此我們建議只使用有狀態(tài)的組件
  • 函數(shù)式組件只能使用接收 propscontext 的普通函數(shù)創(chuàng)建 (即:slotsattrs,emit)。
  • 非兼容變更:functional attribute 在單文件組件 (SFC) <template> 已被移除
  • 非兼容變更:{ functional: true } 選項(xiàng)在通過(guò)函數(shù)創(chuàng)建組件已被移除

更多信息,請(qǐng)繼續(xù)閱讀!

#介紹

在 Vue 2 中,函數(shù)式組件有兩個(gè)主要用例:

  • 作為性能優(yōu)化,因?yàn)樗鼈兊某跏蓟俣缺扔袪顟B(tài)組件快得多
  • 返回多個(gè)根節(jié)點(diǎn)

然而,在 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)組件。

#2.x 語(yǔ)法

使用 <dynamic-heading> 組件,負(fù)責(zé)提供適當(dāng)?shù)臉?biāo)題 (即:h1,h2h3,等等),在 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>

#3.x 語(yǔ)法

#通過(guò)函數(shù)創(chuàng)建組件

現(xiàn)在在 Vue 3 中,所有的函數(shù)式組件都是用普通函數(shù)創(chuàng)建的,換句話說(shuō),不需要定義 { functional: true } 組件選項(xiàng)。

他們將接收兩個(gè)參數(shù):propscontext。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

#單文件組件 (SFC)

在 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ū)別在于:

  1. functional attribute 在 <template> 中移除
  2. listeners 現(xiàn)在作為 $attrs 的一部分傳遞,可以將其刪除

#下一步

有關(guān)新函數(shù)式組件的用法和對(duì)渲染函數(shù)的更改的詳細(xì)信息,見(jiàn):

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)