当前位置: 代码网 > it编程>前端脚本>Vue.js > vue实现简洁文件上传进度条功能

vue实现简洁文件上传进度条功能

2024年06月10日 Vue.js 我要评论
一、效果展示缓若江海凝清光二、代码const uploadprogress = ref(); //上传进度//进度丝滑更新//进度,时常const progresschange = (targetpe

一、效果展示

缓若江海凝清光

二、代码

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上传进度条内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com