You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt Bridge页面切换时加载指示器不显示问题求助

解决Nuxt Bridge页面切换进度条不显示问题

方案一:修复自定义组件的钩子监听逻辑

Nuxt Bridge中,page:start/page:finish这类钩子需要通过useNuxtApp实例绑定,而非直接监听全局事件。以下是可直接复用的自定义进度条组件:

<!-- components/LoadingBar.vue -->
<template>
  <div v-if="isLoading" class="loading-bar" :style="{ width: progress + '%' }"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
const nuxtApp = useNuxtApp()
const isLoading = ref(false)
const progress = ref(0)

const startLoading = () => {
  isLoading.value = true
  progress.value = 0
  const interval = setInterval(() => {
    progress.value += 5
    if (progress.value >= 90) clearInterval(interval)
  }, 100)
}

const finishLoading = () => {
  progress.value = 100
  setTimeout(() => {
    isLoading.value = false
    progress.value = 0
  }, 300)
}

onMounted(() => {
  nuxtApp.hook('page:start', startLoading)
  nuxtApp.hook('page:finish', finishLoading)
})

onUnmounted(() => {
  nuxtApp.unhook('page:start', startLoading)
  nuxtApp.unhook('page:finish', finishLoading)
})
</script>

<style scoped>
.loading-bar {
  position: fixed;
  top: 0;
  left: 0;
  height: 3px;
  background: #42b983;
  transition: width 0.2s ease;
  z-index: 9999;
}
</style>

将组件引入根布局(如layouts/default.vue):

<template>
  <div>
    <LoadingBar />
    <Nuxt />
  </div>
</template>

<script setup>
import LoadingBar from '~/components/LoadingBar.vue'
</script>

方案二:启用Nuxt Bridge兼容的内置进度条

通过配置开启Nuxt 3风格的加载指示器,需先在nuxt.config.js中启用Bridge的App特性:

// nuxt.config.js
export default {
  bridge: {
    app: true // 启用Nuxt 3 App组件相关特性
  },
  app: {
    loadingIndicator: {
      name: 'circle',
      color: '#2563eb',
      background: '#ffffff'
    }
  }
}

创建/修改app.vue(Nuxt Bridge推荐的根入口文件):

<template>
  <NuxtLoadingIndicator />
  <NuxtLayout>
    <NuxtPage />
  </NuxtLayout>
</template>

方案三:兜底方案——监听路由变化

若上述钩子仍不触发,可直接通过Vue Router导航守卫控制进度条:

<!-- components/LoadingBar.vue -->
<template>
  <div v-if="isLoading" class="loading-bar" :style="{ width: progress + '%' }"></div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
const router = useRouter()
const isLoading = ref(false)
const progress = ref(0)

const startLoading = () => {
  isLoading.value = true
  progress.value = 0
  const timer = setInterval(() => {
    progress.value += 10
    if (progress.value >= 90) clearInterval(timer)
  }, 150)
}

const finishLoading = () => {
  progress.value = 100
  setTimeout(() => {
    isLoading.value = false
    progress.value = 0
  }, 200)
}

onMounted(() => {
  router.beforeEach(() => startLoading())
  router.afterEach(() => finishLoading())
})
</script>

内容的提问来源于stack exchange,提问作者Ericlm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 09:25:23