Vue3异步组件【defineAsyncComponent】
我们都知道在 Vue2 也有异步组件的概念,但整体上来说不算完整~,
1、Vue3 提供了
defineAsyncComponent
方法与Suspense
内置组件,我们可以用它们来做一个优雅的异步组件加载方案。2、 异步组件高级声明方法中的
component
选项更名为loader
;2、
loader
绑定的组件加载函数不再接收resolve
和reject
参数,而且必须返回一个Promise
;
直接看代码
首先看Vue2中怎么声明一个异步组件
const asyncPage = () => import('./Lazy.vue') 复制代码
再看Vue3中如何声明一个异步组件: Vue3中声明异步组件,需要使用辅助函数defineAsyncComponent
来声明。如下
<template> <div> <h1>Async Components</h1> <p>异步组件测试</p> <child></child> </div> </template> <script> import { defineAsyncComponent } from 'vue' const child = defineAsyncComponent(() => import('@/components/async-component-child.vue')) export default { name: 'async-components', components:{ 'child': child } }; </script> 复制代码
Vue3 引入
defineAsyncComponent
辅助函数的原因现在,在 Vue 3 中,由于函数组件被定义为纯函数,异步组件定义需要通过将其包装在一个新的 defineAsyncComponent helper 中来显式定义。
更加高级的声明方式 Vue2中使用高级的异步组件方式声明
const asyncPageWithOptions = { component: () => import('./Lazy.vue'), delay: 200, timeout: 3000, error: ErrorComponent, loading: LoadingComponent } 复制代码
Vue3差不多,只需要将component
改为loader
即可
const asyncPageWithOptions = { loader: () => import('./Lazy.vue'), delay: 200, // 在显示 loadingComponent 之前的延迟 | 默认值:200(单位 ms) timeout: 3000, // 如果提供了 timeout ,并且加载组件的时间超过了设定值,将显示错误组件 // 默认值:Infinity(即永不超时,单位 ms) error: ErrorComponent, // 加载失败时要使用的组件 loading: LoadingComponent // 加载异步组件时要使用的组件 } 复制代码
异步组件的实现
// Lazy.vue <template> <div> 异步组件 </div> </template> <script> </script> <style scoped> </style> 复制代码
在其他组件中导入它
<template> <button @click="show = true"> Login </button> <lazy-component v-if="show" /> </template> <script> import { defineAsyncComponent } from 'vue' export default { components:{ "lazy-component": defineAsyncComponent(()=>import('./components/Lazy.vue')) }, data() { return { show: false } } } </script> 复制代码
异步组件有助于我们实现最佳性能。我们只想在我们的页面初始加载时加载需要的组件。有条件渲染的组件在我们的页面加载时往往是不需要的,所以为什么要让我们的应用程序加载它们呢?
作者:5加H
链接:https://juejin.cn/post/7026906794433708039