Vue实现里实现获取数据进度条

前言

实现上传文件的时候或者下载的时候,需要用到进度条

1.vue项目, 用的element ui组件库

代码调用片段:

// 点击下载
    clickDown() {
      // console.log('单个下载')
      let params = {
        'xxx':'xyyxyxy'
      };
      //注意 上传的方式不同 post/get 要区分下
      var config = {
         onUploadProgress :progress=> {//post用这个
           var complete = (Math.round(progress.loaded / progress.total * 100) );
          //这里的complete 加载进度的数字
           this.$set(xxx,'xxxx', complete)
         },
         onDownloadProgress :progress=>{ //get 用这个
          var complete = (Math.round(progress.loaded / progress.total * 100));
           //这里的complete 加载进度的数字
           this.$set(xxx,'xxxx', complete)
         },
      };
	  //downFile 调用接口  别忘了引入 接口 哦 import { downFile} from '.......'

      downFile(params, config).then(res => {
      //顺便写一下用blob 格式接收文件
        const blob = new Blob([res.data]);
        if ("download" in document.createElement("a")) {
          // 非IE下载
          const elink = document.createElement("a");
          elink.download = row.name + "." + row.extType;
          // +'.'+row.extType
          elink.style.display = "none";
          elink.href = window.URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        } else {
          // IE10+下载
          navigator.msSaveBlob(blob, row.name + "." + row.extType);
        }
      });
    },

封装的axios:

//request.js
import axios from 'axios'
let token = ''
export default function (data){
   return axios({
      ...data,
      headers: { 'x-token': token },
   })
}

api.js文件


import request from '@/util/request';//引入
const baseURL = '/api' //proxy里的代理配置
export function downFile(params,config){
   return request({
      method: 'get',
      url: 'xxxxx',
      baseURL,
      params,
      ...config,//把写好的config传过来
      responseType: 'blob' //上传文件的时候用的blob格式
   })
}

注意

request.upload.addEventListener in not a function
如果报上错误,可以看看是否引入了mock.js ,关闭即可,
看一下大佬: 跳转.

关于

关于 onprogress 可以去了解
跳转.

写到这里让我想到了 视频 /音频; 皆可在菜鸟教程找到

HTML 中:
<audio|video onprogress="SomeJavaScriptCode">
//在 JavaScript 中:
<script>
audio|video.onprogress=SomeJavaScriptCode;
//使用 addEventListener():

audio|video.addEventListener("progress", function()
  {
  //SomeJavaScriptCode
  }
);
</script>
Logo

前往低代码交流专区

更多推荐