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

不對的地方還望大家指點,謝謝!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM