vue 动态路由登陆后刷新页面404或者白屏处理方式(非常简单)

先将路由拦截器代码贴上:


// 路由拦截器
router.beforeEach((to, from, next) => {
  NProgress.start()
  // 是否已经加载好路由列表
  if (to.matched.length != 0) {
    if (to.meta.requireAuth) {
      // 判断该路由是否需要登录权限
      if (Boolean(localStorage.getItem('userInfo'))) {
        next()
      } else {
        next({
          path: '/login',
          query: { redirect: to.fullPath } // 将跳转的路由path作为参数,登录成功后跳转到该路由
        })
      }
    } else {
      if (Boolean(localStorage.getItem('userInfo'))) {
        // 判断是否登录
        if (to.path != '/' && to.path != '/login') {
          //判断是否要跳到登录界面
          next()
        } else {
          /**
           * 防刷新,如果登录,修改路由跳转到登录页面,修改路由为登录后的首页
           */
          next({
            path: '/goods/Goods'
          })
        }
      } else {
        next()
      }
    }
  } else {
    //刷新后走的位置
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 将跳转的路由path作为参数,登录成功后跳转到该路由
      })
    
  }
})

刷新后发现match数组长度为0了,看了好多文章才知道是因为vueX刷新之后数据丢失造成路由列表数据丢失,所以匹配不到要进入的路由信息。

解决方法是在检测到数据丢失后重新请求添加路由列表,修改后的代码如下:


// 路由拦截器
router.beforeEach((to, from, next) => {
  NProgress.start()
  // 是否已经加载好路由列表
  if (to.matched.length != 0) {
    if (to.meta.requireAuth) {
      // 判断该路由是否需要登录权限
      if (Boolean(localStorage.getItem('userInfo'))) {
        next()
      } else {
        next({
          path: '/login',
          query: { redirect: to.fullPath } // 将跳转的路由path作为参数,登录成功后跳转到该路由
        })
      }
    } else {
      if (Boolean(localStorage.getItem('userInfo'))) {
        // 判断是否登录
        if (to.path != '/' && to.path != '/login') {
          //判断是否要跳到登录界面
          next()
        } else {
          /**
           * 防刷新,如果登录,修改路由跳转到登录页面,修改路由为登录后的首页
           */
          next({
            path: '/goods/Goods'
          })
        }
      } else {
        next()
      }
    }
  } else {
    //刷新后走的位置
    // 修改:刷新后vuex内的路由列表数据丢失,重新获取路由列表再进行下一步
    if (Boolean(localStorage.getItem('userInfo'))) {
      store.dispatch('getRoutes').then(res => {
        next()
      })
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 将跳转的路由path作为参数,登录成功后跳转到该路由
      })
    }
  }
})
  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值