vue3中suspense的使用


1.作用:suspense在等待異步組件時額外渲染一些內容,使用戶擁有更好的體驗。

2.使用:

 引入異步組件,Child需要在components里注冊
import {defineAsyncComponent} from 'vue' 
// import demo from './components/demo.vue' //靜態引入
const Child = defineAsyncComponent(()=>import('./components/demo.vue'))//動態引入
 使用susoense包裹組件,並配置好default和fallback
<template>
  <!-- vue3中模版結構可以沒有根標簽 -->
  <div class="father">
    <div class="child">
      <teleport to='body'>
        <input type="text" v-model="keyword">
        <h3>{{keyword}}</h3>
      </teleport>
    </div>
    <Suspense>
      <!-- v-slot:default,默認要渲染的組件 -->
      <template v-slot:default>
        <Child></Child>
      </template>
      <!-- v-slot:fallback里面寫組件加載過程中需要顯示的內容 -->
      <template v-slot:fallback>
        <div>
          <h3>加載中,請稍等。。。</h3>
        </div>
      </template>
    </Suspense>
  </div>
</template>

這是我子組件里面寫的內容,方便查看效果

<template>
  <div class="child">
    <div>我是子組件</div>
    <h3>{{sum}}</h3>
  </div>
</template>

<script>
import { ref } from "vue"; export default { name: "HelloWorld", props: { msg: String, }, setup() { const sum = ref(0); return new Promise((resolve, reject) => { setTimeout(() => { resolve(sum); }, 3000); if (sum.value != 0) { setTimeout(() => { reject(sum); }, 3000); } }); }, }; </script> <style scoped> .child { padding: 10px; background-color: #e8f; } </style> 

看看效果:

子組件在等待結果的時候會先渲染fallback里面的內容

 

 加載完成后顯示子組件

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM