LoadingBar 顶部加载条
页面最顶部的一条细进度条,切换路由、提交请求时告诉用户“正在加载”。用函数调用,不用在模板里写组件。
引入
import { HuiLoadingBar } from '@nscode/handy-ui'
基础用法
HuiLoadingBar.start():加载条从页面顶部出现,自动缓慢前进,越接近终点越慢,不会走到头。HuiLoadingBar.finish():走满,再淡出。HuiLoadingBar.error():变成危险色,走满,再淡出。
没点“开始”直接点“完成”或“出错”也可以,加载条从 0 走满再淡出。
<script setup lang="ts">
import { onBeforeUnmount } from 'vue'
import { HuiButton, HuiLoadingBar, HuiSpace } from '@nscode/handy-ui'
// 生命周期示例:LoadingBar基础
let alive = true
onBeforeUnmount(() => {
// 全局条可能已被其他页面复用,离开只作废本例入口。
alive = false
})
const start = () => {
if (alive) HuiLoadingBar.start()
}
const finish = () => {
if (alive) HuiLoadingBar.finish()
}
const error = () => {
if (alive) HuiLoadingBar.error()
}
</script>
<template>
<HuiSpace wrap>
<HuiButton type="primary" @click="start">开始(start)</HuiButton>
<HuiButton type="success" @click="finish">完成(finish)</HuiButton>
<HuiButton type="danger" @click="error">出错(error)</HuiButton>
</HuiSpace>
</template>
重复调用
页面上同一时间只有一条加载条:
- 加载中再次 start(options) 更新 color、height、zIndex,沿用当前进度,不会多出一条。
- 已经在走满、淡出时调用
start,加载条从头开始。 - 已经在走满、淡出时调用
finish不做任何事;调用error只把颜色换成出错色。
<script setup lang="ts">
import { onBeforeUnmount } from 'vue'
import { HuiButton, HuiLoadingBar, HuiSpace } from '@nscode/handy-ui'
// 生命周期示例:LoadingBar重复调用
let timers: ReturnType<typeof setTimeout>[] = []
let alive = true
let version = 0
const cancel = () => {
version++
timers.forEach(clearTimeout)
timers = []
}
// 安排几个延时调用;再点一次时先取消上一次没执行的
const schedule = (steps: [number, () => void][]) => {
if (!alive) return false
cancel()
// 当前按钮显式重演时重置显示;卸载只取消自己的延迟,不清其他页面的条。
HuiLoadingBar.destroy()
const request = version
timers = steps.map(([delay, fn]) =>
setTimeout(() => {
if (alive && request === version) fn()
}, delay)
)
return true
}
// 离开这个页面时取消还没执行的调用
onBeforeUnmount(() => {
alive = false
cancel()
})
// 连着调用 3 次 start,仍然只有一条,2 秒后完成
const startThreeTimes = () => {
if (!schedule([[2000, HuiLoadingBar.finish]])) return
HuiLoadingBar.start()
HuiLoadingBar.start()
HuiLoadingBar.start()
}
// 1 秒后完成,淡出时再 start,加载条从头开始,3 秒后再完成
const restart = () => {
if (
!schedule([
[1000, HuiLoadingBar.finish],
[1400, () => HuiLoadingBar.start()],
[3000, HuiLoadingBar.finish]
])
)
return
HuiLoadingBar.start()
}
// 完成后马上出错:颜色换成危险色,照常淡出
const finishThenError = () => {
if (
!schedule([
[1000, HuiLoadingBar.finish],
[1100, HuiLoadingBar.error]
])
)
return
HuiLoadingBar.start()
}
</script>
<template>
<HuiSpace wrap>
<HuiButton @click="startThreeTimes">连着调用 3 次 start</HuiButton>
<HuiButton @click="restart">淡出时重新 start</HuiButton>
<HuiButton @click="finishThenError">finish 后马上 error</HuiButton>
</HuiSpace>
</template>
颜色和高度
start 可以传配置,只对这一轮生效:
color:进度条颜色,默认主题主色。可以写任意 CSS 颜色,也可以写var(--hui-color-success)这样的主题变量,跟着配色和暗色主题变。errorColor:调用error后的颜色,默认主题危险色。height:高度,数字按 px,字符串原样使用,默认2。
每个按钮开始后 1.5 秒完成,errorColor 一行 1.5 秒后出错:
<script setup lang="ts">
import { onBeforeUnmount } from 'vue'
import { HuiButton, HuiLoadingBar, HuiSpace } from '@nscode/handy-ui'
import type { LoadingBarOptions } from '@nscode/handy-ui'
// 生命周期示例:LoadingBar颜色高度
let timer: ReturnType<typeof setTimeout> | undefined
let alive = true
let version = 0
onBeforeUnmount(() => {
alive = false
version++
clearTimeout(timer)
})
const play = (options: LoadingBarOptions, end: 'finish' | 'error' = 'finish') => {
if (!alive) return
const request = ++version
// 加载中直接更新显示配置,进度保持
clearTimeout(timer)
HuiLoadingBar.start(options)
timer = setTimeout(() => {
timer = undefined
if (alive && request === version) HuiLoadingBar[end]()
}, 1500)
}
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">color</span>
<HuiButton @click="play({})">默认主色</HuiButton>
<HuiButton @click="play({ color: 'var(--hui-color-success)' })">成功色</HuiButton>
<HuiButton @click="play({ color: 'var(--hui-color-warning)' })">警告色</HuiButton>
<HuiButton @click="play({ color: '#722ed1' })">#722ed1</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">errorColor</span>
<HuiButton @click="play({}, 'error')">默认危险色</HuiButton>
<HuiButton @click="play({ errorColor: 'var(--hui-color-warning)' }, 'error')"
>警告色</HuiButton
>
<HuiButton @click="play({ errorColor: '#eb2f96' }, 'error')">#eb2f96</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">height</span>
<HuiButton @click="play({})">默认 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>
全局配置
HuiLoadingBar.config(options) 设置之后每一轮的默认配置,配置项和 start 的一样,和已有的配置合并。某一项传 undefined 恢复成默认值。start 传的配置优先于它。正在显示的加载条不受影响,下一次 start 才用上。一般在应用入口调用一次。
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue'
import { HuiButton, HuiLoadingBar, HuiSpace } from '@nscode/handy-ui'
// 生命周期示例:LoadingBar全局配置
const current = ref('默认')
let timer: ReturnType<typeof setTimeout> | undefined
let alive = true
let version = 0
const setPurple = () => {
if (!alive) return
HuiLoadingBar.config({ color: '#722ed1', height: 4 })
current.value = '紫色、高 4px'
}
const setDefault = () => {
if (!alive) return
HuiLoadingBar.config({ color: undefined, height: undefined })
current.value = '默认'
}
const play = (color?: string) => {
if (!alive) return
const request = ++version
clearTimeout(timer)
HuiLoadingBar.start(color ? { color } : undefined)
timer = setTimeout(() => {
timer = undefined
if (alive && request === version) HuiLoadingBar.finish()
}, 1500)
}
onBeforeUnmount(() => {
clearTimeout(timer)
version++
// 恢复本例展示的默认配置,不结束正在显示的全局加载条。
setDefault()
alive = false
})
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<HuiButton @click="setPurple">config:紫色、高 4px</HuiButton>
<HuiButton @click="setDefault">config:恢复默认</HuiButton>
<span>当前默认配置:{{ current }}</span>
</HuiSpace>
<HuiSpace wrap>
<HuiButton type="primary" @click="play()">start()</HuiButton>
<HuiButton type="primary" plain @click="play('var(--hui-color-success)')">
start({ color: 成功色 })
</HuiButton>
</HuiSpace>
</HuiSpace>
</template>
模拟请求
请求开始时 start,成功时 finish,失败时 error。下面用 setTimeout 模拟一个 1.5 秒的请求:
含延时的示例在卸载时取消本例定时器与后续通知,不在卸载尾部调用全局finish或destroy。模拟请求取消时会结束helper等待,取消不显示失败提示;当前有效请求仍正常显示成功或失败。
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue'
import { HuiButton, HuiLoadingBar, HuiMessage, HuiSpace } from '@nscode/handy-ui'
// 生命周期示例:LoadingBar模拟请求
const loading = ref(false)
let alive = true
let version = 0
const cancellations = new Set<() => void>()
onBeforeUnmount(() => {
alive = false
version++
// 清计时器也结算等待中的helper,取消不会进入失败提示。
for (const cancel of [...cancellations]) cancel()
})
// 模拟请求:1.5 秒后按 ok 成功或失败
const fakeRequest = (ok: boolean): Promise<boolean> => {
if (!alive) return Promise.resolve(false)
return new Promise<boolean>((resolve, reject) => {
const timer = setTimeout(() => {
cancellations.delete(cancel)
if (ok) resolve(true)
else reject(new Error('网络异常'))
}, 1500)
const cancel = () => {
clearTimeout(timer)
cancellations.delete(cancel)
resolve(false)
}
cancellations.add(cancel)
})
}
const submit = async (ok: boolean) => {
if (!alive || loading.value) return
const request = ++version
loading.value = true
HuiLoadingBar.start()
try {
const completed = await fakeRequest(ok)
if (!completed || !alive || request !== version) return
HuiLoadingBar.finish()
HuiMessage.success('提交成功')
} catch {
if (!alive || request !== version) return
HuiLoadingBar.error()
HuiMessage.error('提交失败,请稍后再试')
} finally {
if (alive && request === version) loading.value = false
}
}
</script>
<template>
<HuiSpace wrap>
<HuiButton type="primary" :loading="loading" @click="submit(true)">提交(会成功)</HuiButton>
<HuiButton :loading="loading" @click="submit(false)">提交(会失败)</HuiButton>
</HuiSpace>
</template>
多个请求同时进行
第一个结束的请求调用 finish 时,加载条就走满了。要等所有请求都结束,自己记一下进行中的个数:从 0 变成 1 时 start,回到 0 时 finish。
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue'
import { HuiButton, HuiLoadingBar, HuiSpace } from '@nscode/handy-ui'
// 生命周期示例:LoadingBar并发请求
const pending = ref(0)
const timers = new Set<ReturnType<typeof setTimeout>>()
let alive = true
let version = 0
onBeforeUnmount(() => {
alive = false
version++
for (const timer of timers) clearTimeout(timer)
timers.clear()
})
// 模拟一个请求,duration 毫秒后结束
const request = (duration: number) => {
if (!alive) return
const session = version
if (pending.value === 0) HuiLoadingBar.start()
pending.value++
const timer = setTimeout(() => {
timers.delete(timer)
if (!alive || session !== version) return
pending.value--
if (pending.value === 0) HuiLoadingBar.finish()
}, duration)
timers.add(timer)
}
const sendThree = () => {
request(600)
request(1200)
request(2400)
}
</script>
<template>
<HuiSpace align="center">
<HuiButton type="primary" @click="sendThree">同时发 3 个请求</HuiButton>
<span>进行中的请求:{{ pending }} 个</span>
</HuiSpace>
</template>
配合 vue-router
在路由的 beforeEach 里 start,afterEach 里 finish,onError 里 error:
import {
createRouter,
createWebHistory,
isNavigationFailure,
NavigationFailureType
} from 'vue-router'
import { HuiLoadingBar } from '@nscode/handy-ui'
import routes from './routes'
const router = createRouter({
history: createWebHistory(),
routes
})
// 开始跳转。被重定向时会再进来一次,加载条已经在走,不会重新开始
router.beforeEach(() => {
HuiLoadingBar.start()
})
router.afterEach((to, from, failure) => {
// 跳到当前页面(duplicated)时没有经过 beforeEach;被新的跳转取消(cancelled)时,
// 新的那次结束会 finish。这两种情况不用管,否则会多显示一次走满
if (
isNavigationFailure(failure, NavigationFailureType.duplicated | NavigationFailureType.cancelled)
) {
return
}
HuiLoadingBar.finish()
})
// 守卫里抛了错、路由组件加载失败时,afterEach 不会调用,在这里显示出错
router.onError(() => {
HuiLoadingBar.error()
})
export default router
服务端渲染时这些调用不做任何事,不需要另外判断。
页面祖先变量与显式配置
公开变量按“本轮或全局选项中的显式配置 → 页面祖先公开变量 → 原默认”读取。未配置时,高度仍为2px,常态颜色为主题主色,错误颜色为主题危险色。高度变量 --hui-loading-bar-height、常态颜色 --hui-loading-bar-color 只读取,不再被默认行内高度或显式颜色写回覆盖;错误颜色统一为 --hui-loading-bar-color-error,旧 --hui-loading-bar-error-color 直接迁名,不留旧名兜底。
加载条作为页面服务挂在 body 下,不会继承调用按钮外层容器的变量。可在应用全局样式的 :root 或 body 设置;父组件的 <style scoped> 不能把局部选择器当作这条全局加载条的祖先。本例通过公开API演示页面根变量,离开时恢复原覆盖。
“按页面变量开始”只对本轮传入三个 undefined,让该轮不沿用已有的全局外观选项,再读取页面变量;config 的全局默认仍保留。“按显式配置开始”使用3px、主色和危险色,优先于页面6px、成功色和警告色。原有正数/CSS长度校验、层级、进度、定时器和淡出流程保持。
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue'
import { HuiButton, HuiLoadingBar, HuiSpace } from '@nscode/handy-ui'
// 生命周期示例:LoadingBar页面变量
let alive = true
const themeActive = ref(false)
const status = ref('尚未开始')
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 = () => {
if (!alive) return
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 = () => {
if (!alive) return
const style = document.documentElement.style
for (const [name, saved] of previous) {
// 离开示例时只恢复自己仍持有的覆盖,保留期间其他页面新设的值。
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) => {
if (!alive) return
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
? '本轮显式配置:3px / 主色 / 危险色'
: '本轮读取页面变量;没有变量时使用原默认'
}
const end = (error: boolean) => {
if (!alive || !started.value) return
if (error) HuiLoadingBar.error()
else HuiLoadingBar.finish()
started.value = false
status.value = error ? '错误状态走满后淡出' : '完成后淡出'
}
onBeforeUnmount(() => {
restoreTheme()
alive = false
})
</script>
<template>
<HuiSpace class="loading-bar-variables-demo" direction="vertical" fill>
<p>加载条挂在页面 body 下,本例给页面根设置变量,离开时恢复原覆盖。</p>
<HuiSpace wrap>
<HuiButton class="loading-bar-theme-apply" @click="applyTheme">设置页面变量</HuiButton>
<HuiButton class="loading-bar-theme-restore" @click="restoreTheme">恢复页面变量</HuiButton>
<span class="loading-bar-theme-state"
>页面变量:{{ themeActive ? '6px / 成功色 / 警告色' : '原值' }}</span
>
</HuiSpace>
<HuiSpace wrap>
<HuiButton class="loading-bar-theme-start" @click="start(false)">按页面变量开始</HuiButton>
<HuiButton class="loading-bar-explicit-start" @click="start(true)">按显式配置开始</HuiButton>
<HuiButton class="loading-bar-theme-error" :disabled="!started" @click="end(true)"
>错误</HuiButton
>
<HuiButton class="loading-bar-theme-finish" :disabled="!started" @click="end(false)"
>完成</HuiButton
>
</HuiSpace>
<span class="loading-bar-theme-result">{{ status }}</span>
</HuiSpace>
</template>
方法
| 方法 | 说明 |
|---|---|
HuiLoadingBar.start(options?) | 开始加载。加载中只更新 color、height、zIndex,不重置进度;正在走满、淡出时从头开始。options 只对这一轮生效,优先于 config |
HuiLoadingBar.finish() | 加载完成:走满再淡出。没有 start 过时从 0 走满再淡出;已经在走满、淡出时不做任何事 |
HuiLoadingBar.error() | 加载出错:变成出错色,走满再淡出。没有 start 过时也能调用;已经在走满、淡出时只换颜色 |
HuiLoadingBar.config(options) | 设置之后每一轮的默认配置,和已有的合并,某一项传 undefined 恢复默认。正在显示的加载条不受影响 |
HuiLoadingBar.destroy() | 立即移除加载条,不播放动画,清掉所有计时器。没有加载条时不做任何事 |
这些方法都没有返回值,也不依赖 this,可以解构出来用。
配置项
start 和 config 的参数:
| 配置项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| color | string | --hui-color-primary | 进度条颜色。任意 CSS 颜色,也可以写 var(--hui-color-success) 这样的主题变量 |
| errorColor | string | --hui-color-danger | 调用 error 后的颜色 |
| height | number | string | 2 | 高度,数字按 px,字符串原样使用(如 '0.25rem')。不大于 0 的数字不生效 |
| zIndex | number | 10000 | 层级 |
类型
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
}