vue请求实现进度条
使用axios拦截器实现请求进度条
在Vue项目中安装axios依赖
npm install axios
创建axios实例并添加请求/响应拦截器
import axios from 'axios'
const instance = axios.create({
baseURL: 'https://api.example.com'
})
// 请求拦截器
instance.interceptors.request.use(config => {
// 开始请求时显示进度条
NProgress.start()
return config
})
// 响应拦截器
instance.interceptors.response.use(response => {
// 请求完成时隐藏进度条
NProgress.done()
return response
}, error => {
// 请求出错时也隐藏进度条
NProgress.done()
return Promise.reject(error)
})
export default instance
使用NProgress库显示进度条
安装NProgress
npm install nprogress
在main.js中引入样式
import 'nprogress/nprogress.css'
配置NProgress外观
import NProgress from 'nprogress'
NProgress.configure({
minimum: 0.1,
easing: 'ease',
speed: 500,
trickleRate: 0.02,
trickleSpeed: 200,
showSpinner: false
})
结合Vue Router实现路由切换进度条
在router.js中添加导航守卫
import NProgress from 'nprogress'
router.beforeEach((to, from, next) => {
NProgress.start()
next()
})
router.afterEach(() => {
NProgress.done()
})
使用Element UI的Loading组件实现局部进度
在组件中使用局部加载
methods: {
async fetchData() {
const loading = this.$loading({
lock: true,
text: '加载中...',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
})
try {
const res = await axios.get('/api/data')
// 处理数据
} finally {
loading.close()
}
}
}
自定义进度条组件实现
创建自定义进度条组件
<template>
<div class="progress-container" v-if="visible">
<div class="progress-bar" :style="{ width: progress + '%' }"></div>
</div>
</template>
<script>
export default {
data() {
return {
visible: false,
progress: 0
}
},
methods: {
start() {
this.visible = true
this.progress = 0
this.simulateProgress()
},
simulateProgress() {
const interval = setInterval(() => {
this.progress += Math.random() * 10
if (this.progress >= 100) {
clearInterval(interval)
setTimeout(() => {
this.visible = false
}, 300)
}
}, 300)
}
}
}
</script>
<style scoped>
.progress-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 3px;
background-color: #f0f0f0;
z-index: 9999;
}
.progress-bar {
height: 100%;
background-color: #409eff;
transition: width 0.3s ease;
}
</style>
使用Fetch API实现原生进度监控
利用Fetch API的ReadableStream监控下载进度

async function fetchWithProgress(url, options = {}) {
const response = await fetch(url, options)
if (!response.ok) throw new Error(response.statusText)
if (!response.body) return response.json()
const contentLength = +response.headers.get('Content-Length')
const reader = response.body.getReader()
const chunks = []
let receivedLength = 0
while(true) {
const { done, value } = await reader.read()
if (done) break
chunks.push(value)
receivedLength += value.length
if (contentLength) {
const percent = Math.round((receivedLength / contentLength) * 100)
console.log(`下载进度: ${percent}%`)
// 更新UI进度条
}
}
const chunksAll = new Uint8Array(receivedLength)
let position = 0
for (const chunk of chunks) {
chunksAll.set(chunk, position)
position += chunk.length
}
return new TextDecoder('utf-8').decode(chunksAll)
}






