Files
webapp/app/plugins/route-loading.client.ts

42 lines
808 B
TypeScript

export default defineNuxtPlugin((nuxtApp) => {
const routeLoading = useState<boolean>('route-loading', () => false)
let hideTimer: ReturnType<typeof setTimeout> | null = null
const show = () => {
if (hideTimer) {
clearTimeout(hideTimer)
hideTimer = null
}
routeLoading.value = true
}
const hide = () => {
if (hideTimer) {
clearTimeout(hideTimer)
}
// Small delay to prevent flicker on very fast routes.
hideTimer = setTimeout(() => {
routeLoading.value = false
hideTimer = null
}, 120)
}
nuxtApp.$router.beforeEach((_to, _from, next) => {
show()
next()
})
nuxtApp.$router.afterEach(() => {
hide()
})
nuxtApp.$router.onError(() => {
hide()
})
nuxtApp.hook('page:finish', () => {
hide()
})
})