Vue-router实现单页面应用在没有登陆状况下,自动跳转到登陆页面

这是我作前端一来的第一篇文章,都不知道该怎么开始了。那就直接奔主题吧。先讲讲这个功能的实现场景吧,咱们小组使用vue全家桶实现了一个单页面应用,最初就考虑对登陆状态作限制。好比登陆后不能后退到登陆页面,退出到登陆页面后,不能后退刚刚登陆的页面。在main.js中:前端

new Vue({
  store,
  router
}).$mount('#app')
router.beforeEach((to, from, next) => {
  window.scrollTo(0, 0)
  console.log(1234)
  if (!to.meta.requiresAuth) {
    if (!store.state.collectItems.bAuth) {
      next({
        path: '/'
        // query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    if (store.state.collectItems.bAuth && to.fullPath === '/') {
      console.log()
      next(false)
      return
    }
    next()
  }
})

对那些是登陆才能访问的,那些是没有登陆就能够直接访问的,都作限制。这些功能都是实现的没有问题的。可是发现了一个问题就是,可是发现了一个问题就是你们直接在浏览器的地址栏输入一个登陆后才能访问的页面,虽然不能访问到页面,可是页面会卡在这里不动。本来设置的的路由跳转根本就没有起到做用。后来发现,由于是这块的路由根本就没有发挥做用的时候,页面就已经报错了。有一天忽然和咱们小组的妹子讨论的时候,忽然提到能不能在页面渲染先设置一个路由呢,因而就在 new Vue实例前面加了一个router的判断:vue

router.beforeEach((to, from, next) => {
  if (to.fullPath !== '/') {
    next({
      path: '/'
    })
    return
  }
  next()
})

瞬间以前的问题解决了。如今直接访问那些只有登陆后才能访问的面,就直接跳转到了登陆页面了。

整理后的代码:浏览器

router.beforeEach((to, from, next) => {
  if (to.fullPath !== '/') {
    next({
      path: '/'
    })
    return
  }
  next()
})
new Vue({
  store,
  router
}).$mount('#app')
router.beforeEach((to, from, next) => {
  window.scrollTo(0, 0)
  console.log(1234)
  if (!to.meta.requiresAuth) {
    if (!store.state.collectItems.bAuth) {
      next({
        path: '/'
        // query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    if (store.state.collectItems.bAuth && to.fullPath === '/') {
      console.log()
      next(false)
      return
    }
    next()
  }
})

不对的地方还望你们指点,谢谢!app

相关文章
相关标签/搜索