react & vue & angular

函数式组件 Functional Components

2022-06-16  本文已影响0人  alue

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

  1. 性能优化,函数式组件初始化速度远远快于状态式组件( stateful components)。
  2. 返回多个根节点的场景。

但是,在Vue 3中,状态式组件的性能得到大幅优化,并不比函数式组件差多少。同时,状态式组件也可以返回多个根节点。

因此,Vue 3中,一般来说都推荐使用状态式组件。适合函数式组件只剩下一种使用场景,那就是简单组件,例如动态标题组件。这里,函数式组件因为代码量少,用起来比较清爽。

函数式组件的写法

以动态标题级别为例:

Vue 2 的函数式组件写法

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

SFC中的写法

<!-- Vue 2 Functional Component Example with <template> -->
<template functional>
  <component
    :is="`h${props.level}`"
    v-bind="attrs"
    v-on="listeners"
  />
</template>

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

Vue 3 的函数式组件写法

import { h } from 'vue'

const DynamicHeading = (props, context) => {
  return h(`h${props.level}`, context.attrs, context.slots)
}

DynamicHeading.props = ['level']

export default DynamicHeading

SFC中的写法

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

<script>
export default {
  props: ['level']
}
</script>
上一篇 下一篇

猜你喜欢

热点阅读