49 lines
1.0 KiB
TypeScript
49 lines
1.0 KiB
TypeScript
import { onBeforeUnmount, onMounted, ref } from 'vue'
|
|
|
|
/**
|
|
* 平滑推进 0 → 100 的进度值,到达 100% 时只触发一次回调。
|
|
* 组件卸载(用户中止流程)时会自动取消,不会误跳转。
|
|
*/
|
|
export function useTimedProgress(durationMs: number, onComplete: () => void) {
|
|
const progress = ref(0)
|
|
|
|
let frame = 0
|
|
let startedAt = 0
|
|
let finished = false
|
|
|
|
const tick = (now: number) => {
|
|
if (!startedAt) startedAt = now
|
|
const elapsed = now - startedAt
|
|
progress.value = Math.min(100, (elapsed / durationMs) * 100)
|
|
|
|
if (progress.value >= 100) {
|
|
if (!finished) {
|
|
finished = true
|
|
onComplete()
|
|
}
|
|
return
|
|
}
|
|
|
|
frame = window.requestAnimationFrame(tick)
|
|
}
|
|
|
|
onMounted(() => {
|
|
if (durationMs <= 0) {
|
|
progress.value = 100
|
|
if (!finished) {
|
|
finished = true
|
|
onComplete()
|
|
}
|
|
return
|
|
}
|
|
|
|
frame = window.requestAnimationFrame(tick)
|
|
})
|
|
|
|
onBeforeUnmount(() => {
|
|
window.cancelAnimationFrame(frame)
|
|
})
|
|
|
|
return { progress }
|
|
}
|