1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- import router from './router'
- import store from './store'
- import NProgress from 'nprogress'
- import 'nprogress/nprogress.css'
- import auth from '@/utils/auth'
- NProgress.configure({
- showSpinner: false
- })
- const whiteList = ['/login', '/auth-redirect', '/bind', '/register', '/pay', '/question/preview']
- const uaWhiteList = ['/question/preview']
- router.beforeEach(async(to, from, next) => {
- NProgress.start()
- const token = auth.getToken()
- // 白名单检测
- if (!token && !whiteList.includes(to.path)) {
- next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
- NProgress.done()
- return
- }
- try {
- // 路由智能加载
- const addRoutes = await store.dispatch('CheckRoutes')
- // 用户信息智能加载
- if (token && addRoutes) await store.dispatch('GetInfo')
- // 加入VUE路由 并跳转
- if (addRoutes) {
- next({
- ...to,
- replace: true
- }) // 用replace的方式延迟跳转来保证addRoutes生效了
- } else {
- next()
- }
- } catch (err) {
- console.log('force logout with error', err)
- store.dispatch('LogOut').then(() => {
- next({
- path: '/'
- })
- })
- }
- })
- router.afterEach((to, from) => {
- store.dispatch('SetLocation', { to, from })
- NProgress.done()
- })
|