Vue3.2 如何使用nprogress设置路由加载进度条
安装 nprogresspnpm install --save nprogress封装nprogress// 文件位置:src/utils/nprogress.ts// 引入进度条import NProgress from 'nprogress';import 'nprogress/nprogress.css';//全局进度条的配置NProgress.configure({easing: 'eas
·
- 安装
nprogress
pnpm install --save nprogress
- 封装
nprogress
// 文件位置: src/utils/nprogress.ts
// 引入进度条
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
//全局进度条的配置
NProgress.configure({
easing: 'ease', // 动画方式
speed: 1000, // 递增进度条的速度
showSpinner: false, // 是否显示加载ico
trickleSpeed: 200, // 自动递增间隔
minimum: 0.3 // 初始化时的最小百分比
})
// 打开进度条
export const start = ()=>{
NProgress.start()
}
// 关闭进度条
export const close = ()=>{
NProgress.done()
}
- 在
main.ts
中使用
import userUserStore from '@/store/modules/useUserStore';
import { ElNotification, ElMessage } from 'element-plus';
// 引入封装的nprogress.ts
import { start, close } from '@/utils/nprogress';
const idUser = storeToRefs(userUserStore()).id;
router.beforeEach((to, from, next) => {
start(); //---------------------------------------------->此处开始
// 设置浏览器标题
if (to.meta.title) {
document.title = String(to.meta.title);
} else {
document.title = '滑坡监测平台';
}
// 路由出错处理
if (to.matched.length === 0 && !to.name) {
ElNotification({
title: 'Error',
message: 'This is an error message',
type: 'error',
duration: 5000,
});
ElMessage.error('404');
router.push('/404');
} else if (to.path !== '/login' && to.path !== '/404') {
if (idUser.value === -1) {
console.log('未登录');
ElNotification({
title: '未登录状态',
message: '您当前未登录,请登录后再访问!',
type: 'error',
duration: 5000,
});
ElMessage.error('您当前未登录,请登录后再访问!');
router.push('/login');
}
}
next();
});
// 路由加载结束后执行
router.afterEach(() => {
close();//---------------------------------------------->此处结束
});
- 在封装的
axios
也添加上,请求响应更需要使用
import { ElMessage } from 'element-plus';
// 导入axios
import axios from 'axios';
import { IUser, KEY_USER_ID } from '@/store/modules/useUserStore';
import router from '@/router';
import { start, close } from '@/utils/nprogress';
// 使用element-ui Message做消息提醒
//1. 创建新的axios实例,
const service = axios.create({
// 公共接口--这里注意后面会讲
baseURL: 'http://127.0.0.1:8000/api/v1',
// 超时时间 单位是ms,这里设置了5s的超时时间
timeout: 5 * 1000,
});
// 2.请求拦截器
service.interceptors.request.use(
(config) => {
start();//---------------------------------------------->此处开始
// ...此处省略其它配置
return config;
},
(error) => {
return Promise.reject(error);
}
);
// 3.响应拦截器
service.interceptors.response.use(
(response) => {
//接收到响应数据并成功后的一些共有的处理,关闭loading等
close();//---------------------------------------------->此处结束
return response;
},
(error) => {
// ...此处省略其它配置
return Promise.reject(error);
}
);
//4.导出文件
export default service;
- 更改进度条的颜色、宽度,位置
index.html
中的style
标签中
<style>
#nprogress .bar {
/* 自定义颜色 需要加上!important;,这里加了渐变色 */
background-color: #FFFFFF !important;
background-image: linear-gradient(0deg, #FFFFFF 0%, #6284FF 50%, #FF0000 100%) !important;
height: 6px !important;
}
</style>
- 渐变背景查看地址:https://www.grabient.com/
更多推荐
已为社区贡献5条内容
所有评论(0)