permission.js 1.4 KB
import router from './router'
import store from './store'
import { getMenuInfo } from '@/api/user'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
import Cookies from 'js-cookie'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

router.beforeEach(async (to, from, next) => {
    NProgress.start()
    document.title = getPageTitle(to.meta.title)
    let hasAddDict = store.state.dict.addDict
    let hasAddRoute = store.state.permission.addRoutes
    if (!hasAddDict) {
        store.dispatch('dict/generateDic')
    }
    if (hasAddRoute) {
        next()
        // next({ ...to, replace: true })
    } else {
        const { result: getMenuData } = await getMenuInfo()
        const accessRoutes = await store.dispatch('permission/generateRoutes', getMenuData)
        // 获取用户信息
        await store.dispatch('user/getUserInfo')
        router.addRoutes([...accessRoutes, { path: '*', redirect: '/404', hidden: true }])
        const routeTo = Cookies.get('routerTo')
        console.log(routeTo)
        if (routeTo && routeTo !== '/') {
            next({ ...to, replace: true })
        } else {
            next('/home')
        }
    }
    NProgress.done()
})
router.afterEach(to => {
    // 解决刷新页面报404问题
    Cookies.set("routerTo", to.fullPath)
    NProgress.done()
})