@@ -2,39 +2,41 @@ import { ref } from 'vue';
22
33/** *
44 *
5- * @description 用例模拟进度条进度
6- * @step 增加的步长
5+ * @description 用例模拟进度条进度,采用逐渐减速的曲线,返回的 progress 为整数
6+ * @step 初始衰减速率因子(百分比,表示每次更新增加剩余部分的百分之几),默认2
77 */
88export default function useProgressBar ( step : number = 2 ) {
99 const intervalId = ref < any > ( null ) ;
10- const progress = ref < number > ( 0 ) ;
11- const increment = ref < number > ( step ) ;
10+ const progress = ref < number > ( 0 ) ; // 对外暴露的整数进度
11+ let internalProgress = 0 ; // 内部浮点数进度,用于精确计算
12+ const decayRate = ref < number > ( step / 100 ) ; // 衰减率(小数形式)
1213
13- // 更新进度
14+ // 更新进度:每次增加剩余部分的 decayRate 倍,并对 internalProgress 取整后更新 progress
1415 function updateProgress ( ) {
15- progress . value = Math . floor ( progress . value + increment . value ) ;
16- if ( progress . value >= 100 ) {
17- progress . value = 100 ;
18- }
16+ const remaining = 100 - internalProgress ;
17+ const increment = remaining * decayRate . value ;
18+ internalProgress = Math . min ( internalProgress + increment , 100 ) ;
19+ progress . value = Math . floor ( internalProgress ) ;
1920 }
2021
21- // 完成进度,清理定时器
22+ // 完成进度,立即设置 100% 并清理定时器
2223 function finish ( ) {
2324 clearInterval ( intervalId . value ) ;
2425 progress . value = 100 ;
25- updateProgress ( ) ;
26+ internalProgress = 100 ;
2627 }
2728
2829 // 启动进度条
29- function start ( newStep : number = increment . value ) {
30+ function start ( newStep : number = step ) {
31+ // 清除之前的定时器
32+ if ( intervalId . value ) {
33+ clearInterval ( intervalId . value ) ;
34+ }
3035 progress . value = 0 ;
31- increment . value = newStep ;
36+ internalProgress = 0 ;
37+ decayRate . value = newStep / 100 ;
3238 intervalId . value = setInterval ( ( ) => {
33- if ( progress . value >= 100 ) {
34- finish ( ) ;
35- } else {
36- updateProgress ( ) ;
37- }
39+ updateProgress ( ) ;
3840 } , 100 ) ;
3941 }
4042
0 commit comments