1,安装
npm install --save nprogress
2. 导入
import { configure, start, done } from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
3. 配置
configure({ showSpinner: false }) // NProgress Configuration
4. 使用
// 开启加载提示进度条
start()
// 路由完成之后结束加载提示进度条
done()
下面是我在项目中的使用
import { configure, start, done } from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import Vue from 'vue'
import Router from 'vue-router'
import { getToken } from '@/utils/token'
import getPageTitle from '@/utils/pageTitle'
import constantRoutes from './router'
configure({ showSpinner: false }) // NProgress Configuration
Vue.use(Router)
export const router = new Router({
mode: 'history', // hash
routes: constantRoutes
})
// 白名单页面,不需要登录
const whiteList = ['/login']
router.beforeEach((to, from, next) => {
console.log('to', to)
console.log('from', from)
// 开启加载提示进度条
start()
// 设置浏览器的标题
document.title = getPageTitle(to.meta.title)
const token = getToken()
console.log('token--->', token)
if (token) {
if (to.path === '/401') {
next()
} else {
const routes = router.getRoutes().filter((r) => r.path === to.path)
// 如果目标路由存在
if (routes.length) {
next()
} else {
next('/404')
}
}
} else {
// 白名单中的路由不用登录
if (whiteList.includes(to.path)) {
next()
} else {
next('/login')
}
}
})
router.afterEach((to, from, next) => {
// 路由完成之后结束加载提示进度条
done()
window.scrollTo(0, 0)
})
export default router