functionsetRouter(data){ console.log('data', data) getRouter = [] let children = [] for (const name of data) { children.push({ path: name, name: name, component: '@/views/table/sss', meta: {title: name, icon: 'table'} }) } getRouter.push({ path: '/ss', component: 'Layout', redirect: '/ss/table', name: 'ApiData', meta: {title: 'sss', icon: 'el-icon-s-help'}, children: children }) setLocalStorage(myRouterKey, getRouter) }
router.beforeEach(async(to, from, next) => { // start progress bar NProgress.start()
// set page title document.title = getPageTitle(to.meta.title)
// determine whether the user has logged in const hasToken = getToken()
if (hasToken) { if (to.path === '/login') { // if is logged in, redirect to the home page next({ path: '/' }) NProgress.done() } else { const hasGetUserInfo = store.getters.name if (hasGetUserInfo) { next() } else { try { // get user info await store.dispatch('user/getInfo') //不加这个判断,路由会陷入死循环 if (getRouter.length === 0) { if(!getLocalStorage(myRouterKey)){ console.log('read from axios') axios.get('http://xx.com/getProjectList', {timeout: 5000}).then(res => { setRouter(res.data) addRouter(to, next) }).catch(err =>{ console.error('addRouter', err) setRouter(['xxx']) addRouter(to, next) }) }else{ console.log('read from local') getRouter = JSON.parse(getLocalStorage(myRouterKey)) addRouter(to, next) } }else{ console.log('next') next() } } catch (error) { // remove token and go to login page to re-login await store.dispatch('user/resetToken') console.error(error.message) Message({ message: error.message, type: 'error', duration: 5 * 1000 }) await MessageBox.confirm('登录失败,请刷新重试', { confirmButtonText: '确定', type: 'error' }) next(`/login?redirect=${to.path}`) NProgress.done() } } } } else { /* has no token*/
if (whiteList.indexOf(to.path) !== -1) { // in the free login whitelist, go directly next() } else { // other pages that do not have permission to access are redirected to the login page. next(`/login`) NProgress.done() } } })
router.afterEach(() => { // finish progress bar NProgress.done() })