LoadingBar
A thin progress bar at the top of the page indicates loading during navigation or requests. Use its function API; no template component is needed.
Import
import { HuiLoadingBar } from '@nscode/handy-ui'
Basic Usage
HuiLoadingBar.start(): shows the bar at the top of the page. Progress advances automatically and slows near the end without reaching it.HuiLoadingBar.finish(): completes the bar, then fades it out.HuiLoadingBar.error(): switches to the danger color, completes the bar, then fades it out.
You can call Finish or Error without first calling Start. The bar completes from 0 and fades out.
<script setup lang="ts">
import { onBeforeUnmount } from 'vue'
import { HuiButton, HuiLoadingBar, HuiSpace } from '@nscode/handy-ui'
// Remove any running bar when leaving this page
onBeforeUnmount(() => HuiLoadingBar.destroy())
</script>
<template>
<HuiSpace wrap>
<HuiButton type="primary" @click="HuiLoadingBar.start()">Start (start)</HuiButton>
<HuiButton type="success" @click="HuiLoadingBar.finish()">Finish (finish)</HuiButton>
<HuiButton type="danger" @click="HuiLoadingBar.error()">Error (error)</HuiButton>
</HuiSpace>
</template>
Repeated Calls
Only one loading bar appears on the page at a time:
- Calling
start(options)while loading updatescolor,heightandzIndexwithout resetting progress or creating another bar. - Calling
startduring completion or fade-out restarts the bar. - Calling
finishduring completion or fade-out has no effect. Callingerroronly changes the color to the error color.
<script setup lang="ts">
import { onBeforeUnmount } from 'vue'
import { HuiButton, HuiLoadingBar, HuiSpace } from '@nscode/handy-ui'
let timers: ReturnType<typeof setTimeout>[] = []
const cancel = () => {
timers.forEach(clearTimeout)
timers = []
HuiLoadingBar.destroy()
}
// Schedule calls; another click cancels calls still pending from the previous run
const schedule = (steps: [number, () => void][]) => {
cancel()
timers = steps.map(([delay, fn]) => setTimeout(fn, delay))
}
// Cancel pending calls when leaving this page
onBeforeUnmount(cancel)
// Three start calls still create one bar; finish after 2 seconds
const startThreeTimes = () => {
schedule([[2000, HuiLoadingBar.finish]])
HuiLoadingBar.start()
HuiLoadingBar.start()
HuiLoadingBar.start()
}
// Finish after 1 second, restart during fade-out, then finish after 3 seconds
const restart = () => {
schedule([
[1000, HuiLoadingBar.finish],
[1400, () => HuiLoadingBar.start()],
[3000, HuiLoadingBar.finish]
])
HuiLoadingBar.start()
}
// Error immediately after finish: switch to the danger color and fade out as usual
const finishThenError = () => {
schedule([
[1000, HuiLoadingBar.finish],
[1100, HuiLoadingBar.error]
])
HuiLoadingBar.start()
}
</script>
<template>
<HuiSpace wrap>
<HuiButton @click="startThreeTimes">Call start 3 times</HuiButton>
<HuiButton @click="restart">Restart during fade-out</HuiButton>
<HuiButton @click="finishThenError">Error immediately after finish</HuiButton>
</HuiSpace>
</template>
Color and Height
Options passed to start apply to the current run only:
color: progress color, using the theme primary color by default. Accepts any CSS color or a theme variable such asvar(--hui-color-success), which follows the color scheme and dark theme.errorColor: color aftererroris called; defaults to the theme danger color.height: numbers use pixels; strings are used as provided. Defaults to2.
Each button finishes after 1.5 seconds. Buttons in the errorColor row report an error after 1.5 seconds instead.
<script setup lang="ts">
import { HuiButton, HuiLoadingBar, HuiSpace } from '@nscode/handy-ui'
import type { LoadingBarOptions } from '@nscode/handy-ui'
let timer: ReturnType<typeof setTimeout> | undefined
const play = (options: LoadingBarOptions, end: 'finish' | 'error' = 'finish') => {
// Update appearance while loading without resetting progress
clearTimeout(timer)
HuiLoadingBar.start(options)
timer = setTimeout(() => HuiLoadingBar[end](), 1500)
}
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">color</span>
<HuiButton @click="play({})">Default primary color</HuiButton>
<HuiButton @click="play({ color: 'var(--hui-color-success)' })">Success color</HuiButton>
<HuiButton @click="play({ color: 'var(--hui-color-warning)' })">Warning color</HuiButton>
<HuiButton @click="play({ color: '#722ed1' })">#722ed1</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">errorColor</span>
<HuiButton @click="play({}, 'error')">Default danger color</HuiButton>
<HuiButton @click="play({ errorColor: 'var(--hui-color-warning)' }, 'error')"
>Warning color</HuiButton
>
<HuiButton @click="play({ errorColor: '#eb2f96' }, 'error')">#eb2f96</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">height</span>
<HuiButton @click="play({})">Default 2</HuiButton>
<HuiButton @click="play({ height: 4 })">4</HuiButton>
<HuiButton @click="play({ height: 6 })">6</HuiButton>
<HuiButton @click="play({ height: '0.5rem' })">'0.5rem'</HuiButton>
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 80px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
Global Configuration
HuiLoadingBar.config(options) merges defaults for subsequent runs with the existing configuration. Options match those of start. Pass undefined for an option to restore its default. Options passed to start take precedence. The currently displayed bar is unaffected; changes apply on the next start. Usually call this once at application startup.
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue'
import { HuiButton, HuiLoadingBar, HuiSpace } from '@nscode/handy-ui'
const current = ref('Default')
let timer: ReturnType<typeof setTimeout> | undefined
const setPurple = () => {
HuiLoadingBar.config({ color: '#722ed1', height: 4 })
current.value = 'Purple, 4px high'
}
const setDefault = () => {
HuiLoadingBar.config({ color: undefined, height: undefined })
current.value = 'Default'
}
const play = (color?: string) => {
clearTimeout(timer)
HuiLoadingBar.start(color ? { color } : undefined)
timer = setTimeout(() => HuiLoadingBar.finish(), 1500)
}
// config is global; restore defaults on unmount to avoid affecting other pages
onBeforeUnmount(setDefault)
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<HuiButton @click="setPurple">config: Purple, 4px high</HuiButton>
<HuiButton @click="setDefault">config: restore defaults</HuiButton>
<span>Current defaults: {{ current }}</span>
</HuiSpace>
<HuiSpace wrap>
<HuiButton type="primary" @click="play()">start()</HuiButton>
<HuiButton type="primary" plain @click="play('var(--hui-color-success)')">
start({ color: Success color })
</HuiButton>
</HuiSpace>
</HuiSpace>
</template>
Simulating a Request
Call start when a request begins, finish on success and error on failure. This example uses setTimeout to simulate a 1.5-second request:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiLoadingBar, HuiMessage, HuiSpace } from '@nscode/handy-ui'
const loading = ref(false)
// Simulate a request that succeeds or fails after 1.5 seconds according to ok
const fakeRequest = (ok: boolean) =>
new Promise<void>((resolve, reject) => {
setTimeout(() => (ok ? resolve() : reject(new Error('Network error'))), 1500)
})
const submit = async (ok: boolean) => {
loading.value = true
HuiLoadingBar.start()
try {
await fakeRequest(ok)
HuiLoadingBar.finish()
HuiMessage.success('Submitted successfully')
} catch {
HuiLoadingBar.error()
HuiMessage.error('Submission failed. Try again later')
} finally {
loading.value = false
}
}
</script>
<template>
<HuiSpace wrap>
<HuiButton type="primary" :loading="loading" @click="submit(true)">Submit (succeeds)</HuiButton>
<HuiButton :loading="loading" @click="submit(false)">Submit (fails)</HuiButton>
</HuiSpace>
</template>
Concurrent Requests
Calling finish when the first request ends completes the bar. To wait for all requests, track the number in flight: call start when the count changes from 0 to 1, and finish when it returns to 0.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiLoadingBar, HuiSpace } from '@nscode/handy-ui'
const pending = ref(0)
// Simulate a request that completes after duration milliseconds
const request = (duration: number) => {
if (pending.value === 0) HuiLoadingBar.start()
pending.value++
setTimeout(() => {
pending.value--
if (pending.value === 0) HuiLoadingBar.finish()
}, duration)
}
const sendThree = () => {
request(600)
request(1200)
request(2400)
}
</script>
<template>
<HuiSpace align="center">
<HuiButton type="primary" @click="sendThree">Send 3 concurrent requests</HuiButton>
<span>Requests in flight: {{ pending }} requests</span>
</HuiSpace>
</template>
Using vue-router
Call start in beforeEach, finish in afterEach and error in onError:
import {
createRouter,
createWebHistory,
isNavigationFailure,
NavigationFailureType
} from 'vue-router'
import { HuiLoadingBar } from '@nscode/handy-ui'
import routes from './routes'
const router = createRouter({
history: createWebHistory(),
routes
})
// Start navigation. Redirects call this again; an active bar keeps its current progress
router.beforeEach(() => {
HuiLoadingBar.start()
})
router.afterEach((to, from, failure) => {
// Duplicated navigation skips beforeEach. For navigation cancelled by a newer navigation,
// the newer navigation calls finish. Ignore these failures to avoid an extra completion animation
if (
isNavigationFailure(failure, NavigationFailureType.duplicated | NavigationFailureType.cancelled)
) {
return
}
HuiLoadingBar.finish()
})
// Guard errors and route component loading failures skip afterEach; report an error here
router.onError(() => {
HuiLoadingBar.error()
})
export default router
These calls do nothing during server rendering, so no additional environment check is required.
Page Ancestor Variables and Explicit Options
Appearance resolves in this order: an explicit option for the current run or global configuration, a public variable on a page ancestor, then the original default. Without configuration, height remains 2px, the normal color uses the theme primary color and the error color uses the theme danger color. --hui-loading-bar-height and --hui-loading-bar-color are read only; default inline height and explicit colors no longer overwrite them. The error variable is --hui-loading-bar-color-error. The old --hui-loading-bar-error-color is renamed directly, without a fallback alias.
As a page service, the bar is attached under body and does not inherit variables from the container surrounding the triggering button. Set variables on :root or body in global application styles. A selector in a parent component's <style scoped> does not become an ancestor of this global bar. This example uses public APIs to change page root variables and restores its original overrides on unmount.
Start with page variables passes three undefined values for the current run, bypassing existing global appearance options before reading page variables. Global config defaults remain intact. Start with explicit options uses 3px, primary and danger colors, taking precedence over the page's 6px, success and warning colors. Positive-number/CSS-length validation, stacking, progress, timers and fade-out behavior remain unchanged.
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue'
import { HuiButton, HuiLoadingBar, HuiSpace } from '@nscode/handy-ui'
const themeActive = ref(false)
const status = ref('Not started')
const started = ref(false)
const themeValues: Record<string, string> = {
'--hui-loading-bar-height': '6px',
'--hui-loading-bar-color': 'var(--hui-color-success)',
'--hui-loading-bar-color-error': 'var(--hui-color-warning)'
}
const previous = new Map<string, { value: string; priority: string }>()
const applyTheme = () => {
const style = document.documentElement.style
for (const [name, value] of Object.entries(themeValues)) {
if (!previous.has(name))
previous.set(name, {
value: style.getPropertyValue(name),
priority: style.getPropertyPriority(name)
})
style.setProperty(name, value)
}
themeActive.value = true
}
const restoreTheme = () => {
const style = document.documentElement.style
for (const [name, saved] of previous) {
// On unmount, restore only overrides still owned by this example; preserve newer values from other pages.
if (
style.getPropertyValue(name) !== themeValues[name] ||
style.getPropertyPriority(name) !== ''
)
continue
if (saved.value) style.setProperty(name, saved.value, saved.priority)
else style.removeProperty(name)
}
previous.clear()
themeActive.value = false
}
const start = (explicit: boolean) => {
HuiLoadingBar.destroy()
HuiLoadingBar.start(
explicit
? { height: 3, color: 'var(--hui-color-primary)', errorColor: 'var(--hui-color-danger)' }
: { height: undefined, color: undefined, errorColor: undefined }
)
started.value = true
status.value = explicit
? 'Explicit options: 3px / primary / danger'
: 'Reading page variables; using original defaults when unset'
}
const end = (error: boolean) => {
if (!started.value) return
if (error) HuiLoadingBar.error()
else HuiLoadingBar.finish()
started.value = false
status.value = error
? 'Complete in the error state, then fade out'
: 'Fade out after completion'
}
onBeforeUnmount(() => {
HuiLoadingBar.destroy()
restoreTheme()
})
</script>
<template>
<HuiSpace class="loading-bar-variables-demo" direction="vertical" fill>
<p>
The bar is attached under body. This example sets page root variables and restores its
original overrides on unmount.
</p>
<HuiSpace wrap>
<HuiButton class="loading-bar-theme-apply" @click="applyTheme">Set page variables</HuiButton>
<HuiButton class="loading-bar-theme-restore" @click="restoreTheme"
>Restore page variables</HuiButton
>
<span class="loading-bar-theme-state"
>Page variables: {{ themeActive ? '6px / success / warning' : 'Original values' }}</span
>
</HuiSpace>
<HuiSpace wrap>
<HuiButton class="loading-bar-theme-start" @click="start(false)"
>Start with page variables</HuiButton
>
<HuiButton class="loading-bar-explicit-start" @click="start(true)"
>Start with explicit options</HuiButton
>
<HuiButton class="loading-bar-theme-error" :disabled="!started" @click="end(true)"
>Error</HuiButton
>
<HuiButton class="loading-bar-theme-finish" :disabled="!started" @click="end(false)"
>Finish</HuiButton
>
</HuiSpace>
<span class="loading-bar-theme-result">{{ status }}</span>
</HuiSpace>
</template>
Methods
| Method | Description |
|---|---|
HuiLoadingBar.start(options?) | Starts loading. While loading, updates only color, height and zIndex without resetting progress. Restarts during completion or fade-out. options apply only to this run and take precedence over config |
HuiLoadingBar.finish() | Completes the bar, then fades it out. Without a previous start, completes from 0. Does nothing during completion or fade-out |
HuiLoadingBar.error() | Changes to the error color, completes and fades out. Can be called without start. During completion or fade-out, only changes the color |
HuiLoadingBar.config(options) | Merges defaults for subsequent runs. Pass undefined for an option to restore its default. Does not affect the currently displayed bar |
HuiLoadingBar.destroy() | Immediately removes the bar without animation and clears all timers. Does nothing when no bar exists |
All methods return nothing and do not depend on this, so they can be destructured.
Options
Arguments for start and config:
| Option | Type | Default | Description |
|---|---|---|---|
| color | string | --hui-color-primary | Progress color. Accepts any CSS color or a theme variable such as var(--hui-color-success) |
| errorColor | string | --hui-color-danger | Color after error is called |
| height | number | string | 2 | Height. Numbers use pixels; strings are used as provided, such as '0.25rem'. Numbers less than or equal to 0 are ignored |
| zIndex | number | 10000 | Stacking order |
Types
import type { LoadingBarOptions, LoadingBarApi } from '@nscode/handy-ui'
interface LoadingBarOptions {
color?: string
errorColor?: string
height?: number | string
zIndex?: number
}
interface LoadingBarApi {
start: (options?: LoadingBarOptions) => void
finish: () => void
error: () => void
config: (options: LoadingBarOptions) => void
destroy: () => void
}