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
}