浏览器加载进度条
安装
html
<script src='nprogress.js'></script>
<link rel='stylesheet' href='nprogress.css'/>
或
bash
npm install --save nprogress
引用
js
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css' // Progress 进度条样式
全局引用
js
// main.js
//引入nprogress 进度条插件
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// 配置进度条参数 showSpinner:进度环,minimum:最小百分比,ease:动画和速度,trickleRate:每次步进增长多少
NProgress.configure({ showSpinner: false, minimum: 0.2, easeing: 'swing', speed: 1000, trickleRate: 0.2 })
进度条颜色
css
// APP.vue
// 顶部进度条颜色
#nprogress .bar { background: #2d9 !important; }
调用接口时使用
js
// api/index.js
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// 配置进度条参数 showSpinner:进度环,minimum:最小百分比,ease:动画和速度,trickleRate:每次步进增长多少
NProgress.configure({ showSpinner: false, minimum: 0.2, easeing: 'swing', speed: 1000, trickleRate: 0.2 })
// 防止多次请求进度条重复加载
let loadingNum = 0
function startLoading () {
if (loadingNum === 0) {
NProgress.start()
}
loadingNum++
}
function endLoading () {
loadingNum--
if (loadingNum <= 0) {
NProgress.done()
}
}
// 创建axios实例
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, //URL地址 环境变量文件
timeout: 5000 ,//超时
})
// 请求拦截器
service.interceptors.request.use(
config => {
// 开启进度条
startLoading();
return config
},
error => {
return Promise.reject(error)
}
)
// 响应拦截器
service.interceptors.response.use(
response =>{
// 关闭进度条
endLoading()
return Promise.reject(response)
},
error => {
// 关闭进度条
endLoading()
return Promise.reject(error)
}
)
export default service;
在路由切换中使用
js
import Vue from 'vue'
import VueRouter from 'vue-router'
import NProgress from 'nprogress'
Vue.use(VueRouter);
export const constRouter = [
{
path: '/login',
component: () => import('@/views/login/Login'),
},
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes: constRouter
})
// 页面路由刚开始切换的时候
router.beforeEach(async (to,from,next) => {
// 开启进度条
NProgress.start();
})
// 页面路由切换完毕的时候
router.afterEach(() => {
// 关闭进度条
NProgress.done()
})
export default router