vue实现加载条
使用 NProgress 实现加载条
NProgress 是一个轻量级的进度条库,适用于 Vue 项目。安装 NProgress:
npm install nprogress
在 Vue 项目中引入并使用:
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// 在路由守卫中调用
router.beforeEach((to, from, next) => {
NProgress.start()
next()
})
router.afterEach(() => {
NProgress.done()
})
自定义 CSS 加载条
在 Vue 组件中创建一个简单的 CSS 加载条:
<template>
<div class="loading-bar" v-if="isLoading">
<div class="bar"></div>
</div>
</template>
<script>
export default {
data() {
return {
isLoading: false
}
}
}
</script>
<style>
.loading-bar {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 3px;
background-color: #f3f3f3;
z-index: 9999;
}
.bar {
height: 100%;
width: 0%;
background-color: #42b983;
animation: loading 2s ease-in-out infinite;
}
@keyframes loading {
0% { width: 0%; }
50% { width: 50%; }
100% { width: 100%; }
}
</style>
使用 Vue 过渡效果
利用 Vue 的过渡系统创建加载效果:
<template>
<transition name="fade">
<div v-if="loading" class="loading-overlay">
<div class="loading-spinner"></div>
</div>
</transition>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
.loading-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(255,255,255,0.8);
z-index: 9999;
display: flex;
justify-content: center;
align-items: center;
}
.loading-spinner {
width: 50px;
height: 50px;
border: 5px solid #f3f3f3;
border-top: 5px solid #3498db;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
使用第三方组件库
Element UI 等组件库提供现成的加载组件:
import { Loading } from 'element-ui'
// 全局方法
let loadingInstance = Loading.service({
lock: true,
text: '加载中',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
})
// 关闭加载
loadingInstance.close()
进度条与 Axios 拦截器结合
在 Axios 请求拦截器中显示加载条:
import axios from 'axios'
axios.interceptors.request.use(config => {
NProgress.start()
return config
})
axios.interceptors.response.use(response => {
NProgress.done()
return response
}, error => {
NProgress.done()
return Promise.reject(error)
})






