vue 监听路由刷新跳转,根据是否登录设置路由规则

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/haeasringnar/article/details/82530383

在vue项目中,一个可行的路由规则很重要,它决定着用户是否有权限进入的路由,已经某些路由在刷新时要跳转等等
这部分代码是使用vue全家桶之一的router完成的,下面看具体实例

const whiteList = ['/login']  // 路由白名单,不需要登录的路由放在这里面
router.beforeEach((to,from,next) => {
  // 监听路由刷新进行跳转
  window.addEventListener('load',function () {
    console.log(from.path)
    console.log(to.path)
    if (to.path == '/groupwork') {
      next({ path: '/choice_course' })
    }
  })
  if (store.state.token) {
    if (to.path === '/login') { // 如果当前用户输入的是登录路由,那么就定向到 /choice_course 路由
      next('/choice_course')
    } else {
      if (!store.state.nickname) { // 判断用户信息是否存在,不存在就拉取用户信息
        store.dispatch('GetInfo').then(res => { // 拉取用户信息
          next()
        }).catch((err) => {
          store.dispatch('FedLogOut').then(() => {  // 发生错误就直接清除token,重新登录
            next({ path: '/login' })
          })
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
    }
  }
})

猜你喜欢

转载自blog.csdn.net/haeasringnar/article/details/82530383