本篇文章同步發表於 2023 iThome 鐵人賽:Nuxt.js 3.x 筆記-打造 SSR 專案
Nuxt3 提供了預設進度條元件 <NuxtLoadingIndicator>,在路徑切換時顯示。也可以自訂共用元件來調整觸發時機或樣式。
路由切換(Page Navigation)Loading
方法一:
Nuxt3 內建元件,在頁面切換時觸發
使用方式:
在 app.vue 或是 layouts 加上 <NuxtLoadingIndicator>
Props 選項:
- color:loading bar 顏色,預設為漸層色
- height:loading bar 高度,預設 3(px)
- duration:loading bar 持續時間,預設 2000(毫秒)
- throttle:節流時間,會隱藏 loading bar,預設 200(毫秒)
|
注意:Nuxt ≥ 3.1.0 需加上
:throttle="0",否則受節流時間影響看不到 loading 效果(參考討論串)
方法二:自訂 Loading Indicator
建立 Loading 元件,使用參數 isLoading 判斷是否顯示 Loading Indicator,接著透過 Nuxt app runtime hooks 建立攔截器,這裡使用 page:start 以及 page:finish
|
在 app.vue 加入自訂元件
|
效果如下:
資料請求(Data Fetching)Loading
使用 useFetch 或 useAsyncData Composables,參數 pending 為布林值,顯示資料是否還在請求狀態,用來判斷是否顯示 Loading Indicator
Nuxt3
useFetch相關知識,可以參考 這篇文章
|
效果如下:
參考資源:
https://medium.com/@flanker72/nuxt3-complex-solutions-page-loading-indicator-e34b5a86be52
https://nuxt.com/docs/api/components/nuxt-loading-indicator
https://nuxt.com/docs/getting-started/data-fetching
Nuxt3 入門:打造 SSR 專案
評論