Skip to content

函数式组件

在 Vue 2 中,函数式组件主要有两个应用场景:

  • 作为性能优化,因为它们的初始化速度比有状态组件快得多
  • 返回多个根节点

然而,在 Vue 3 中,有状态组件的性能已经提高到它们之间的区别可以忽略不计的程度。此外,有状态组件现在也支持返回多个根节点。

  • 因此,函数式组件剩下的唯一应用场景就是简单组件,比如创建动态标题的组件。否则,建议你像平常一样使用有状态组件。

2.x

通过单文件组件编写:

vue
<script>
export default {
  functional: true,
  props: ['level'],
  render(h, { props, data, children }) {
    return h(`h${props.level}`, data, children)
  },
}
</script>

或者,对单文件组件中使用 <template> 的写法:

vue
<template functional>
  <component :is="`h${props.level}`" v-bind="attrs" v-on="listeners" />
</template>

<script>
export default {
  props: ['level'],
}
</script>

3.x

通过函数创建组件

在 Vue 3 中,所有的函数式组件都是用普通函数创建的。换句话说,不需要定义 { functional: true } 组件选项:

js
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 中,有状态组件和函数式组件之间的性能差异已经大大减少,并且在大多数用例中是微不足道的。

因此,在单文件组件上使用 functional 的开发者的迁移路径是删除该 attribute

vue
<template>
  <component v-bind:is="`h${$props.level}`" v-bind="$attrs" />
</template>

<script>
export default {
  props: ['level'],
}
</script>

主要的区别在于:

  • <template> 中移除 functional attribute
  • listeners 现在作为 $attrs 的一部分传递,可以将其删除

基于 MIT 许可发布