How to deal with lazy loading in Vue 3?
In Vue 3, lazy loading is handled differently than in Vue 2. Vue 3 recommends using
Suspense
anddefineAsyncComponent
to implement lazy loading of components.
Suspense
Component is a new component in Vue 3, which is used to handle the loading status of asynchronous components. We canSuspense
usefallback
the attribute in to specify a loading placeholder, and the real content will not be displayed until the asynchronous component is loaded.
defineAsyncComponent
It is a new way to define asynchronous components in Vue 3. It returns a Promise object that resolves to a component options object before the component is requested, thereby enabling asynchronous component loading.
Here is an example of using Suspense
and defineAsyncComponent
to implement lazy loading of components:
<template>
<div>
<h1>Lazy Component Demo</h1>
<Suspense>
<template #default>
<AsyncComponent />
</template>
<template #fallback>
<p>Loading...</p>
</template>
</Suspense>
</div>
</template>
<script>
import {
defineAsyncComponent } from 'vue';
const AsyncComponent = defineAsyncComponent({
loader: () => import('./AsyncComponent.vue'),
delay: 200, //延迟时间
timeout: 3000, //超时时间
errorComponent: () => 'Oops, something went wrong!',
loadingComponent: () => 'Loading component...',
});
export default {
components: {
AsyncComponent,
},
};
</script>
That’s the end here, I hope it helps.