vue路由守衛實現登錄狀態管理

有了這段代碼,再也不用擔心每進入一個頁面發送一次checkLogin請求驗證了

過多的名詞等下次再來解釋

看下面兩部分:

1、路由文件

    // 登陸頁面不需要檢測狀態,所以不需要守衛
    // login
    {
      path: '/login',
      name: 'login',
      component: Login,
      meta: {
        title: '登錄'
      }
    },
    // home頁面需要進行登陸狀態驗證,所以增加路由元信息,mate裏面設置要不要守衛
    // home
    {
      path: '/',
      name: 'home',
      component: Home,
      meta: {
        requireLogin: true,
        title: '歡迎回來'
      }
    }

2、hook文件

router.beforeEach(async (to, from, next) => {
    Vue.prototype.$admin = Vue.prototype.$admin || {}
    // check
        // 檢驗不需要登陸狀態的路由
        if (!to.meta.requireLogin) {
            //檢驗不需要登陸狀態路由是否含有狀態儲存
            if (!Vue.prototype.$admin.status) {
                // 如果沒有狀態,進行請求
                let res = await Vue.prototype.$api.get('/api')
                Vue.prototype.$admin = res.data || {}
            }
            next()
        } else {
        // 檢驗需要登陸狀態的路由
            // 檢驗需要登陸狀態路由是否含有狀態儲存
        if (Vue.prototype.$admin.status) {
            // 有就繼續
            next()
        } else {
            // 沒有就請求
            let res = await Vue.prototype.$api.get('/api')
            if (res.data.status == '已登陸') {
                Vue.prototype.$admin = res.data
                next()
            } else {
                // 請求狀態未登錄就返回登陸頁面
                next('/login')
            }
        }
    }
})

然後就達到了:不管跳轉多少頁面,就只發送一次checkLogin的請求的效果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章