日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > vue >内容正文

vue

vue文件下载进度条

發(fā)布時(shí)間:2024/1/8 vue 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 vue文件下载进度条 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Step1:封裝download方法

// 通用下載方法 export function download(url, params, filename) {let downProgress = {}let uniSign = new Date().getTime() + '' // 可能會連續(xù)點(diǎn)擊下載多個(gè)文件,這里用時(shí)間戳來區(qū)分每一次下載的文件return axios.post(url, params, {transformRequest: [(params) => {return tansParams(params)}],headers: {'Content-Type': 'application/x-www-form-urlencoded'},responseType: 'blob',onDownloadProgress(progress) {// console.log(progress)// progress對象中的loaded表示已經(jīng)下載的數(shù)量,total表示總數(shù)量,這里計(jì)算出百分比downProgress = Math.round(100 * progress.loaded / progress.total)// 將此次下載的文件名和下載進(jìn)度組成對象再用vuex狀態(tài)管理store.commit('downLoadProgress/SET_PROGRESS', { path: uniSign, 'progress': downProgress })}}).then((data) => {// 文件流傳輸完成后,開啟文件下載const content = dataconst blob = new Blob([content])if ('download' in document.createElement('a')) {const elink = document.createElement('a')elink.download = filename || url.split('/')[url.split('/').length - 1]elink.style.display = 'none'elink.href = URL.createObjectURL(blob)document.body.appendChild(elink)elink.click()URL.revokeObjectURL(elink.href)document.body.removeChild(elink)} else {navigator.msSaveBlob(blob, filename)}}).catch((r) => {console.error(r)this.$message.error('該文件無法下載')}) }/*** 參數(shù)處理* @param {*} params 參數(shù)*/ export function tansParams(params) {let result = ''for (const propName of Object.keys(params)) {const value = params[propName];var part = encodeURIComponent(propName) + "=";if (value !== null && typeof (value) !== "undefined") {if (typeof value === 'object') {for (const key of Object.keys(value)) {if (value[key] !== null && typeof (value[key]) !== 'undefined') {let params = propName + '[' + key + ']';var subPart = encodeURIComponent(params) + "=";result += subPart + encodeURIComponent(value[key]) + "&";}}} else {result += part + encodeURIComponent(value) + "&";}}}return result }

Step2:main.js中全局引入

這一步是為了方便日后調(diào)用,可以省略

import {download} from '@/utils/download' Vue.prototype.download = download

Step3:加入Vuex,在store中添加downLoadProgress模塊

1. 在store/modules下增加downLoadProgress.js文件

//downLoadProgress.js const state = {progressList: [] // 文件下載進(jìn)度列表 }const mutations = {SET_PROGRESS: (state, progressObj) => { // 修改進(jìn)度列表if (state.progressList.length) { // 如果進(jìn)度列表存在if (state.progressList.find(item => item.path == progressObj.path)) { // 前面說的path時(shí)間戳是唯一存在的,所以如果在進(jìn)度列表中找到當(dāng)前的進(jìn)度對象state.progressList.find(item => item.path == progressObj.path).progress = progressObj.progress // 改變當(dāng)前進(jìn)度對象的progress}} else {state.progressList.push(progressObj) // 當(dāng)前進(jìn)度列表為空,沒有下載任務(wù),直接將該進(jìn)度對象添加到進(jìn)度數(shù)組內(nèi)}},DEL_PROGRESS: (state, props) => {state.progressList.splice(state.progressList.findIndex(item => item.path == props), 1) // 刪除進(jìn)度列表中的進(jìn)度對象} } const actions = {} export default {namespaced: true,state,mutations,actions }

2.在store的index.js中添加downLoadProgress模塊

import Vue from 'vue' import Vuex from 'vuex' import app from './modules/app' import user from './modules/user' import tagsView from './modules/tagsView' import permission from './modules/permission' import settings from './modules/settings' import getters from './getters' import downLoadProgress from './modules/downLoadProgress'Vue.use(Vuex)const store = new Vuex.Store({modules: {app,user,tagsView,permission,settings,downLoadProgress},getters })export default store

Step4:在mixins文件夾下增加downloadProgress.js混入

src/mixins/downloadProgress.js

import { mapState } from 'vuex'export const downloadProgress = {name: 'downLoadProgress',computed: {...mapState({'progressList': state => state.downLoadProgress.progressList})},data() {return {notify: {} // 用來維護(hù)下載文件進(jìn)度彈框?qū)ο?/span>}},watch: { // 監(jiān)聽進(jìn)度列表progressList: {handler(n) {console.log(n)let data = JSON.parse(JSON.stringify(n))data.forEach(item => {const domList = [...document.getElementsByClassName(item.path)]if (domList.find(i => i.className == item.path)) { // 如果頁面已經(jīng)有該進(jìn)度對象的彈框,則更新它的進(jìn)度progressdomList.find(i => i.className == item.path).innerHTML = item.progress + '%'} else {if (item.progress === null) { // 此處容錯(cuò)處理,如果后端傳輸文件流報(bào)錯(cuò),刪除當(dāng)前進(jìn)度對象this.$store.commit('downLoadProgress/DEL_PROGRESS', item.path)return}// 如果頁面中沒有該進(jìn)度對象所對應(yīng)的彈框,頁面新建彈框,并在notify中加入該彈框?qū)ο?#xff0c;屬性名為該進(jìn)度對象的path(上文可知path是唯一的),屬性值為$notify(element ui中的通知組件)彈框?qū)ο?/span>this.notify[item.path] = this.$notify.success({// title: 'Info',dangerouslyUseHTMLString: true,message: `<p style="width: 100px;">正在下載<span class="${item.path}" style="float: right">${item.progress}%</span></p>`, // 顯示下載百分比,類名為進(jìn)度對象的path(便于后面更新進(jìn)度百分比)showClose: false,duration: 0})}console.log(item.progress + '%', '-------------------------->')if (item.progress == 100) { // 如果下載進(jìn)度到了100%,關(guān)閉該彈框,并刪除notify中維護(hù)的彈框?qū)ο?/span>this.notify[item.path].close()// delete this.notify[item.path] 上面的close()事件是異步的,這里直接刪除會報(bào)錯(cuò),利用setTimeout,將該操作加入異步隊(duì)列setTimeout(() => {delete this.notify[item.path]}, 1000)this.$store.commit('downLoadProgress/DEL_PROGRESS', item.path)// 刪除downLoadProgress中state的progressList中的進(jìn)度對象}})},deep: true}} }

Step5: 頁面調(diào)用

1. 在需要下載的頁面引入downloadProgress.js

import {downloadProgress} from '@/mixins/downloadProgress.js' export default {name: 'mcu',mixins:[downloadProgress],data() {return {}}... }

2. 調(diào)用方法

downloadFile() {let url = '***/***';this.download(url, '', '下載進(jìn)度測試'); }

頁面效果

總結(jié)

以上是生活随笔為你收集整理的vue文件下载进度条的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。