vue2升级vue3:异步组件defineAsyncComponent
Author:zhoulujun Date:
vue3 异步组件
关于vue3 异步组件,可以参看官方文档:
https://vuejs.org/guide/components/async.html
https://staging-cn.vuejs.org/guide/components/async.html
总结如下:
Vue3 提供了 defineAsyncComponent 方法与 Suspense 内置组件,我们可以用它们来做一个优雅的异步组件加载方案。
异步组件高级声明方法中的 component 选项更名为loader;
loader绑定的组件加载函数不再接收resolve和reject参数,而且必须返回一个Promise;
Vue3 引入defineAsyncComponent 辅助函数的原因
现在,在 Vue 3 中,由于函数组件被定义为纯函数,异步组件定义需要通过将其包装在一个新的 defineAsyncComponent helper 中来显式定义。
改造案例
之前在vue2 异步组件:
import meta from './plugin.json';
const ChartPanel = async () => await import('./components/chart-panel');
const PropsPanel = async () => await import('./components/props-panel');
export default {
ChartPanel,
PropsPanel,
meta,
};
到了vue3
import { defineAsyncComponent } from 'vue';
import meta from './plugin.json';
const ChartPanel = defineAsyncComponent(() => import('./components/chart-panel'));
const PropsPanel = defineAsyncComponent(() => import('./components/props-panel'));
export default {
ChartPanel,
PropsPanel,
meta,
};
更加高级的声明方式
Vue2中使用高级的异步组件方式声明
const asyncPageWithOptions = {
component: () => import('./Lazy.vue'),
delay: 200,
timeout: 3000,
error: ErrorComponent,
loading: LoadingComponent
}
Vue3差不多,只需要将component改为loader即可
Vue3中使用高级的异步组件方式声明
const asyncPageWithOptions = {
loader: () => import('./Lazy.vue'),
delay: 200,
// 在显示 loadingComponent 之前的延迟 | 默认值:200(单位 ms)
timeout: 3000,
// 如果提供了 timeout ,并且加载组件的时间超过了设定值,将显示错误组件
// 默认值:Infinity(即永不超时,单位 ms)
error: ErrorComponent,
// 加载失败时要使用的组件
loading: LoadingComponent
// 加载异步组件时要使用的组件
}
转载本站文章《vue2升级vue3:异步组件defineAsyncComponent》,
请注明出处:https://www.zhoulujun.cn/html/webfront/ECMAScript/vue3/8851.html