Home > Article > Web Front-end > How to use the Suspense component in Vue 3 to achieve data loading transition effects
How to use the Suspense component in Vue 3 to achieve data loading transition effects
Introduction:
As the complexity of web applications increases, the data loading transition effect becomes meets an important user experience requirement. Vue 3 has made further improvements in this area and introduced the Suspense component to solve this problem. This article will introduce how to use the Suspense component in Vue 3 to achieve data loading transition effects, and attach corresponding code examples.
<template> <Suspense> <template #default> <AsyncComponent/> </template> <template #fallback> <loading-component/> </template> </Suspense> </template>
const AsyncComponent = defineAsyncComponent( () => import('./AsyncComponent.vue'), { loadingComponent: loadingComponent, errorComponent: errorComponent, delay: 200, // 延迟200毫秒显示loading状态 timeout: 3000 // 3秒超时时间 } );
<template> <div class="loading">数据加载中...</div> </template> <script> export default { name: 'loadingComponent' } </script> <style scoped> .loading { display: flex; justify-content: center; align-items: center; height: 100px; background-color: #f5f5f5; } </style>
<template> <div> <h1>{{title}}</h1> <p>{{content}}</p> </div> </template> <script> export default { name: 'AsyncComponent', data() { return { title: '', content: '' } }, created() { fetch('/api/data') .then(response => response.json()) .then(data => { this.title = data.title; this.content = data.content; }) .catch(error => { console.error(error); }); } } </script>
<template> <Suspense> <template #default> <AsyncComponent/> </template> <template #fallback> <loading-component/> </template> </Suspense> </template> <script> import { defineAsyncComponent, Suspense } from 'vue'; import AsyncComponent from './AsyncComponent.vue'; import LoadingComponent from './LoadingComponent.vue'; export default { name: 'App', components: { AsyncComponent, LoadingComponent } } </script>
Conclusion:
The Suspense component in Vue 3 allows us to more easily implement data loading transition effects. By introducing the Suspense component, defining asynchronous components and custom loading status components, we can easily achieve the transition effect of data loading and improve user experience. I hope this article is helpful to you, thank you for reading!
The above is the detailed content of How to use the Suspense component in Vue 3 to achieve data loading transition effects. For more information, please follow other related articles on the PHP Chinese website!