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的判断:

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()
  }
})

不对的地方还望大家指点,谢谢!

原文地址:https://www.cnblogs.com/10manongit/p/12898745.html