组件

本文共--字 阅读约--分钟 | 浏览: -- Last Updated: 2021-03-22

函数式组件

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

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

然而,在 Vue 3 中,有状态组件的性能已经提高到可以忽略不计的程度。此外,有状态组件现在还包括返回多个根节点的能力。

因此,函数式组件剩下的唯一用例就是简单组件,比如创建动态标题的组件。

// Vue 2 函数式组件示例
export default {
  functional: true,
  props: ['level'],
  render(h, { props, data, children }) {
    return h(`h${props.level}`, data, children)
  }
}

Vue2.0 使用template:

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

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

3.x语法

import { h } from 'vue'

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

DynamicHeading.props = ['level']

export default DynamicHeading

在 Vue 3 中,所有的函数式组件都是用普通函数创建的,换句话说,不需要定义 { functional: true } 组件选项。他们将接收两个参数:propscontextcontext 参数是一个对象,包含组件的 attrsslots,和 emit property。

在 Vue 3 中,使用SFC template的开发人员,迁移路径是删除该 attribute,并将 props 的所有引用重命名为 $props,将 attrs 重命名为 $attrs

<!-- listeners 现在作为 $attrs 的一部分传递,可以将其删除 -->
<template>
  <component
    v-bind:is="`h${$props.level}`"
    v-bind="$attrs"
  />
</template>

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

异步组件

以前,异步组件是通过将组件定义为返回 Promise 的函数来创建的,例如:

const asyncPage = () => import('./NextPage.vue')

// 或者更高阶的带有选项的组件语法
const asyncPage = {
  component: () => import('./NextPage.vue'),
  delay: 200,
  timeout: 3000,
  error: ErrorComponent,
  loading: LoadingComponent
}

现在,在 Vue 3 中,由于函数式组件被定义为纯函数,因此异步组件的定义需要通过将其包裹在新的 defineAsyncComponent 助手方法中来显式地定义:

import { defineAsyncComponent } from 'vue'
import ErrorComponent from './components/ErrorComponent.vue'
import LoadingComponent from './components/LoadingComponent.vue'

// 不带选项的异步组件
const asyncPage = defineAsyncComponent(() => import('./NextPage.vue'))

// 带选项的异步组件
const asyncPageWithOptions = defineAsyncComponent({
  loader: () => import('./NextPage.vue'), // component 选项现在被重命名为 loader,以便准确地传达不能直接提供组件定义的信息。
  delay: 200,
  timeout: 3000,
  errorComponent: ErrorComponent,
  loadingComponent: LoadingComponent
})

此外,与 2.x 不同,loader 函数不再接收 resolvereject 参数,且必须始终返回 Promise

// 2.x 版本
const oldAsyncComponent = (resolve, reject) => {
  /* ... */
}

// 3.x 版本
const asyncComponent = defineAsyncComponent(
  () =>
    new Promise((resolve, reject) => {
      /* ... */
    })
)

另一个关于组件的变化,就是之前提到的 emits 选项,组件事件需要在 emits 选项中声明。