Suspense

业务方向

骨架屏, 过渡窗口,等待中

vue3- Suspense

基于更好的异步组件实现方式

基本思路

  1. <Suspense>
  2. <template #default>
  3. <h3>
  4. 需要异步数据返回的组件
  5. </h3>
  6. </template>
  7. <template #callback>
  8. <h1>用于显示laoding等待过渡的组件</h1>
  9. </template>
  10. </Suspense>

Loading过渡组件内部实现

  1. <template>
  2. <h1>一个异步小组件</h1>
  3. </template>
  4. <script>
  5. function sleep(timeout) {
  6. return new Promise(resolve => setTimeout(resolve, timeout));
  7. }
  8. export default {
  9. name: "AsyncComponent",
  10. props: {
  11. timeout: {
  12. type: Number,
  13. required: true
  14. }
  15. },
  16. async setup(props) {
  17. await sleep(props.timeout);
  18. }
  19. };
  20. </script>
  1. <template>
  2. <h1>Supense</h1>
  3. <Suspense>
  4. <template #default>
  5. <AsyncComponent :timeout="3000" />
  6. </template>
  7. <template #fallback>
  8. <h1>加载中</h1>
  9. </template>
  10. </Suspense>
  11. </template>
  12. <script>
  13. import AsyncComponent from './AsyncComponent.vue'
  14. export default {
  15. components:{
  16. AsyncComponent
  17. }
  18. }
  19. </script>