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

相關文章
相關標籤/搜索