Vue-router beforeEach登錄鑒權

全局前置守衛

router.beforeEach((to, from, next) => {
  // ...
})

每個守衛方法接收三個參數:

  • to: 即將要進入的目標路由對象

  • from: 當前導航正要離開的路由

  • next: 一定要調用該方法來 resolve 這個鉤子。執行效果依賴 next 方法的調用參數。

    • next() : 進行管道中的下一個鉤子。如果全部鉤子執行完了,則導航的狀態就是 confirmed (確認的)。
    • next(false) : 中斷當前的導航。如果瀏覽器的 URL 改變了 (可能是用戶手動或者瀏覽器后退按鈕),那么 URL 地址會重置到 from 路由對應的地址。
    • next('/') 或者 next({ path: '/' }) : 跳轉到一個不同的地址。當前的導航被中斷,然后進行一個新的導航。你可以向 next 傳遞任意位置對象,且允許設置諸如 replace: truename: 'home' 之類的選項以及任何用在 router-linkto proprouter.push 中的選項。
    • next(error) : (2.4.0+) 如果傳入 next 的參數是一個 Error 實例,則導航會被終止且該錯誤會被傳遞給 router.onError() 注冊過的回調。

登錄鑒權(需要在登錄成功的時候修改跳轉邏輯)

router.beforeEach((to, from, next) => {
  document.title=to.meta.title //設置當前頁的title
  if (to.matched.some(record => record.meta.auth)) {
    if (localStorage.getItem('access_token')) {
        next()
    } else {
      if (to.name === 'Login') {//防止next無限循環的問題
        next();
        return
      }
      next({
        path: '/Login',
        query: {
          redirect: to.fullPath
        }
      });
    }
  } else {
    next()
  }

})

登錄成功返回將要跳轉的頁面且返回上一頁不是登錄頁

api.login().then((res) => {
        if (res.success) {
          localStorage.setItem("access_token", res.token);
          //有redirect登錄成功返回將要跳轉的頁面且返回上一頁不是登錄頁
          let redirect=this.$route.query.redirect; 
          redirect ? this.$router.replace(redirect) : this.$router.push("/");
          //或者 登錄頁直接登錄,登錄成功返回將要跳轉的頁面且返回上一頁不是登錄頁
          let redirect=this.$route.query.redirect || '/';
          this.$router.replace(redirect);
        }
      });

不需要在登錄成功中處理跳轉

router.beforeEach((to, from, next) => {
  document.title = to.meta.title
  if (to.matched.some(record => record.meta.auth)) {
    if (localStorage.getItem('access_token')) {
      if (Object.keys(from.query).length === 0) {//判斷路由來源是否有query,處理不是目的跳轉的情況
        next()
      } else {
        let redirect = from.query.redirect//如果來源路由有query
        if (to.fullPath === redirect) {//這行是解決next無限循環的問題
          next()
        } else {
          next({ path: redirect, replace: true })//跳轉到目的路由
        }
      }
    } else {
      if (to.name === 'Login') {
        next();
        return
      }
      next({
        path: '/Login',
        query: {
          redirect: to.fullPath
        }
      });
    }
  } else {
    next()
  }

})

直接登錄頁登錄成功跳轉到將要去的界面點擊瀏覽器返回上一頁不是登錄頁

this.$router.replace('/')
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容