一、效果展示
二、代码
const uploadprogress = ref(); //上传进度 //进度丝滑更新 //进度,时常 const progresschange = (targetpercent: number, duration: number) => { //performance.now() 是浏览器提供的一个高性能时间 api,它返回一个 domhighrestimestamp, //这个时间戳提供了当前页面从加载到现在所经过的毫秒数,具有很高的精度,适合用来测量脚本执行时间、动画帧间隔等 const starttime = performance.now(); //获取当前进度 const startpercent = uploadprogress.value; const step = (currenttime: number) => { // 计算当前进度 const elapsedtime = currenttime - starttime; // 修改进度条的百分比实现动画效果 let currentpercent = easeinout( elapsedtime, startpercent, targetpercent - startpercent, duration ); // 确保百分比不超过100且不小于0 currentpercent = math.min(math.max(currentpercent, 0), 100); // 更新进度条 uploadprogress.value = math.round(currentpercent); // 如果动画未结束,继续执行动画 if (currentpercent < 100 && elapsedtime < duration) { requestanimationframe(step); } else { uploadprogress.value = math.round(targetpercent); // 确保最终值准确无误 } }; // 使用函数使动画更加平滑 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)); }; }
三、实现原理
1.通过performance.now()获取动画的时间戳,用于创建流畅的动画。
2.通过一个缓动函数来实现动画的过渡效果。
3.通过requestanimationframe这个api来更新动画帧,优化显示效果。
到此这篇关于vue:实现丝滑文件上传进度条的文章就介绍到这了,更多相关vue上传进度条内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论