vue實現(xiàn)簡潔文件上傳進度條功能
一、效果展示

二、代碼
const uploadProgress = ref(); //上傳進度
//進度絲滑更新
//進度,時常
const ProgressChange = (targetPercent: number, duration: number) => {
//performance.now() 是瀏覽器提供的一個高性能時間 API,它返回一個 DOMHighResTimeStamp,
//這個時間戳提供了當前頁面從加載到現(xiàn)在所經(jīng)過的毫秒數(shù),具有很高的精度,適合用來測量腳本執(zhí)行時間、動畫幀間隔等
const startTime = performance.now();
//獲取當前進度
const startPercent = uploadProgress.value;
const step = (currentTime: number) => {
// 計算當前進度
const elapsedTime = currentTime - startTime;
// 修改進度條的百分比實現(xiàn)動畫效果
let currentPercent = easeInOut(
elapsedTime,
startPercent,
targetPercent - startPercent,
duration
);
// 確保百分比不超過100且不小于0
currentPercent = Math.min(Math.max(currentPercent, 0), 100);
// 更新進度條
uploadProgress.value = Math.round(currentPercent);
// 如果動畫未結(jié)束,繼續(xù)執(zhí)行動畫
if (currentPercent < 100 && elapsedTime < duration) {
requestAnimationFrame(step);
} else {
uploadProgress.value = Math.round(targetPercent); // 確保最終值準確無誤
}
};
// 使用函數(shù)使動畫更加平滑
const easeInOut = (t: number, b: number, c: number, d: number) => {
t /= d / 2;
if (t < 1) return (c / 2) * t * t * t + b;
t -= 2;
return (c / 2) * (t * t * t + 2) + b;
};
requestAnimationFrame(step);
};
//選擇文件
const handleFileChange = async (event: any) => {
uploadProgress.value = 0;
const file = event.target.files[0];
fileNmae.value = file.name;
if (file) {
const reader = new FileReader();
const updateProgress = (event: ProgressEvent) => {
if (event.lengthComputable) {
const totalDuration = 1000; // 1秒,單位為毫秒
const percentComplete = (event.loaded / event.total) * 100;
ProgressChange(percentComplete, totalDuration);
}
};
reader.readAsDataURL(file);
reader.onprogress = updateProgress;
reader.onload = (e) => {
if (typeof e.target?.result == "string") {
imageUrl.value = e.target.result;
}
reader.onprogress = null;
fileInfo.size = Number((file.size / 1024).toFixed(2));
};
}三、實現(xiàn)原理
1.通過performance.now()獲取動畫的時間戳,用于創(chuàng)建流暢的動畫。
2.通過一個緩動函數(shù)來實現(xiàn)動畫的過渡效果。
3.通過requestAnimationFrame這個API來更新動畫幀,優(yōu)化顯示效果。
到此這篇關(guān)于vue:實現(xiàn)絲滑文件上傳進度條的文章就介紹到這了,更多相關(guān)vue上傳進度條內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue-music關(guān)于Player播放器組件詳解
這篇文章主要為大家詳細介紹了vue-music關(guān)于Player播放器組件的相關(guān)資料,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11
vue3使用particles插件實現(xiàn)粒子背景的方法詳解
這篇文章主要為大家詳細介紹了vue3使用particles插件實現(xiàn)粒子背景的方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-03-03
使用vue3-print-nb實現(xiàn)打印pdf分頁代碼示例
這篇文章主要介紹了使用vue3-print-nb實現(xiàn)打印pdf分頁的相關(guān)資料,這種方法不僅適用于Vue3項目,也可以在其他前端框架中實現(xiàn)類似的打印分頁功能,需要的朋友可以參考下2024-10-10
vue項目中axios請求網(wǎng)絡(luò)接口封裝的示例代碼
這篇文章主要介紹了vue項目中axios請求網(wǎng)絡(luò)接口封裝的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12
vue.js中關(guān)于點擊事件方法的使用(click)
這篇文章主要介紹了vue.js中關(guān)于點擊事件方法的使用(click),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08

