iT邦幫忙

2023 iThome 鐵人賽

DAY 17
0
Vue.js

Nuxt.js 3.x 筆記-打造 SSR 專案系列 第 17

D17:Nuxt 3.x 自訂 Loading 效果

  • 分享至 

  • xImage
  •  

本篇文章同步更新於個人部落格,歡迎交流指教~謝謝您的閱讀

Nuxt3 提供了預設進度條元件 <NuxtLoadingIndicator>,在路徑切換時顯示。也可以自訂共用元件來調整觸發時機或樣式。

路由切換(Page Navigation)Loading

方法一:<NuxtLoadingIndicator>

Nuxt3 內建元件,在頁面切換時觸發

使用方式:

app.vue 或是 layouts 加上 <NuxtLoadingIndicator>

Props 選項:

  • color: loading bar 顏色,預設為漸層色
  • height: loading bar 高度,預設 3(px)
  • duration: loading bar 持續時間,預設 2000(毫秒)
  • throttle: 節流時間,會隱藏 loading bar,預設 200(毫秒)
// app.vue
<template>
  <div>
    <NuxtLoadingIndicator :throttle="0" />
    <NuxtPage />
  </div>
</template>

注意:Nuxt ≥ 3.1.0 需加上 :throttle="0",否則受節流時間影響看不到 loading 效果(參考討論串

方法二:自訂 Loading Indicator

建立 Loading 元件,使用參數 isLoading 判斷是否顯示 Loading Indicator,接著透過 Nuxt app runtime hooks 建立攔截器,這裡使用 page:start 以及 page:finish

// components/CustomLoadingIndicator.vue
<template>
  <div class="loading-indicator" :class="{ 'show': isLoading }">
    Loading...
  </div>
</template>

<script setup>
const nuxtApp = useNuxtApp();
const isLoading = ref(false);

nuxtApp.hook('page:start', () => {
  isLoading.value = true;
});

nuxtApp.hook('page:finish', () => {
  setTimeout(() => {
    isLoading.value = false;
   }, 200);
});
</script>

<style lang="scss" scoped>
.loading-indicator {
  opacity: 0;
  transition: opacity 0.5s ease-in-out;
  &.show {
    opacity: 1;
    transition: opacity 0.2s ease-in-out;
  }
}
</style>

app.vue 加入自訂元件

// app.vue
<template>
  <div>
    <CustomLoadingIndicator />
    <NuxtPage />
  </div>
</template>

效果如下:

Yes


資料請求(Data Fetching)Loading

使用 useFetchuseAsyncData Composables,參數 pending 為布林值,顯示資料是否還在請求狀態,用來判斷是否顯示 Loading Indicator

Nuxt3 useFetch 相關知識,可以參考 這篇文章

// pages/about.vue
<template>
  <div>
    <div v-if="pending">
      Loading ...
    </div>
    <div v-else>
      user: <pre>{{ data }}<pre>
      <button type="button" @click="refresh()">refresh</button>
    </div>
  </div>
</template>

<script setup>
const { data, pending, refresh } = useFetch('/api/about');
</script>

效果如下:

Yes


參考資源:
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


上一篇
D16:Nuxt 3.x Meta Tags 與 SEO 搜尋引擎優化
下一篇
D18:Nuxt 3.x 搭配 CSS Framework-以 Bootstrap 5 為例
系列文
Nuxt.js 3.x 筆記-打造 SSR 專案30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
Dylan
iT邦新手 3 級 ‧ 2023-10-11 15:47:36

結尾的 效果如下: 是不是缺了圖片啊?🤔

天哪!真是感謝你的提醒,已補上兩支影片

我要留言

立即登入留言