美文网首页
13-全局路由守卫

13-全局路由守卫

作者: 云桃桃 | 来源:发表于2019-08-26 12:59 被阅读0次

其实和之前做的项目基本一样,取token,来验证用户信息,画个流程图就清晰多了,可根据业务需求再做处理。


全局路由守卫.png
import router from './router/index'
import store from './store/index'
import { getToken } from '@/utils/auth' // get token from localStorage
const whiteList = ['/login', '/auth-redirect'] // 白名单

router.beforeEach(async(to, from, next) => {
    // 确定用户是否有token 
    const hasToken = getToken()
    const hasRoles = store.getters.roles && store.getters.roles.length > 0
    if (hasToken) {
        if (to.path === '/login') {
            next()
        } else {
            try {
                if (hasRoles && to.path) {
                    next()
                } else {
                    // 解决了刷新问题
                    console.log('有token-无角色')
                    // 获取用户信息的角色  是一个array
                    const { roles } = await store.dispatch('user/getInfo')
                    const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
                    router.addRoutes(accessRoutes)
                    next({path:to.path,replace:true});
                }
            } catch (error) {
                console.log('无path')
                // remove token and go to login page to re-login
                await store.dispatch('user/resetToken')
                Message.error('Has Error')
                next(`/login`)
            }
        }
        return

    } 
    /* 无需token的页面*/
    if (whiteList.indexOf(to.path) !== -1) {
        console.log('---------白名单')
        // in the free login whitelist, go directly
        next()
    } else {
        console.log('---------回调到登录咯')
        // other pages that do not have permission to access are redirected to the login page.
        next(`/login?redirect=${to.path}`)
    }
})

相关文章

  • 13-全局路由守卫

    其实和之前做的项目基本一样,取token,来验证用户信息,画个流程图就清晰多了,可根据业务需求再做处理。全局路由守...

  • vue的路由守卫

    路由守卫分3种:全局守卫路由独享守卫组件内的路由守卫 1.全局守卫:beforeEachbeforeResolve...

  • vue-路由导航守卫&异步组件

    导航守卫包括全局导航守卫、路由守卫、组件局部守卫 全局导航守卫 在全局导航守卫中,每次路由的跳转他们三个都会被触发...

  • vue-router 常见导航守卫

    全局守卫vue-router全局有三个守卫 路由独享守卫如果你不想全局配置守卫的话,你可以为某些路由单独配置守卫 ...

  • 华云

    一,vue路由守卫的生命周期1,全局的前置路由守卫 router.beforeEach()2, 全局解析守卫 ...

  • vue学习(52)vue-router(4)

    路由守卫作用:对路由进行权限控制分类:全局守卫、独享守卫、组件内守卫全局守卫(我们可以在meta中配置一些信息) ...

  • vue学习笔记(八)导航守卫(全局守卫,路由独享,组件内守卫)

    导航守卫-全局守卫 导航守卫-路由独享 导航守卫-组件内守卫

  • 路由

    全局守卫就是每一个路径进来都会经过这个全局守卫的处理 单路由守卫就是把守卫指定给某一个路由 组件内路由就是把守卫放...

  • Vue 路由守卫

    全局路由守卫 全局前置路由守卫 每次路由切换之前被调用、初始化的时候被调用,写到 router/index.js ...

  • 路由守卫

    路由守卫分为三种 全局守卫: 路由独享守卫卸载route里 组件内守卫:写在组件配置对象里

网友评论

      本文标题:13-全局路由守卫

      本文链接:https://www.haomeiwen.com/subject/yfprectx.html