How to deal with lazy loading in Vue 3?

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 Suspenseand defineAsyncComponentto implement lazy loading of components.

SuspenseComponent is a new component in Vue 3, which is used to handle the loading status of asynchronous components. We can Suspenseuse fallbackthe attribute in to specify a loading placeholder, and the real content will not be displayed until the asynchronous component is loaded.

defineAsyncComponentIt 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 Suspenseand defineAsyncComponentto 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.

Guess you like

Origin blog.csdn.net/weixin_71893790/article/details/135302821