使用vue-admin-template模 vue-router3 刷新后页面空白

导读:本篇文章讲解 使用vue-admin-template模 vue-router3 刷新后页面空白,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

问题:

使用了panjiachen的模版: vue-admin-template,做的后台管理系统。(http://panjiachen.github.io/vue-admin-template)

在配置权限的时候,动态添加路由之后:

 SET_RESULTASYNCROUTES: (state, routes) => {
    state.resultAsyncRoutes = routes
    state.resultAllRoutes = constantRoutes.concat(state.resultAsyncRoutes, anyRoutes)
    //给路由器添加新路由
    router.addRoutes(state.resultAllRoutes) // 动态添加路由:不执行上会跳转失败:路由更新之后,需要重新调用此

  }

手动去刷新页面时会出现空白:

使用vue-admin-template模 vue-router3 刷新后页面空白

 原因分析:

看路由信息,动态路由加进去了,但是在页面刷新后,页面中的路由等信息被重新初始化,但并不等同于项目重启,动态路由添加的内容未被执行,导致只保留了固定路由的部分,所以页面刷新后,会重定向到404界面

解决方法

前置守卫router.beforeEach()配置时候,在异步try-catch里面的next(),改成:

next({…to,replace:true})

或者:next({…to})

//next()->nex({...to,replace:true}) 前置路由守卫
router.beforeEach(async (to, from, next) => {
  // start progress bar
  console.log('..to', to)
  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 { //异步try catch
          // get user info
          console.log('需要先截取token')
          await store.dispatch('user/getInfo')
          next({...to,replace:true}) //重新进入to界面,replace: true表示浏览器不需要记录本次历史
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has 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?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

注:设置 replace 属性的话,当点击时,会调用 router.replace() 而不是 router.push(),于是导航后不会留下 history 记录。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/101525.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!