vue用戶登錄狀態判斷


之前項目中用來判斷是否登錄我寫了多種方案,但是最終只有一個方案是比較好的,這篇博客就是分享該方案;

先說基本要求:

  • 項目中的登錄狀態是依據服務器里的狀態來作為判斷依據;
  • 每一個需要登錄后才能操作的接口,如果未登錄都會返回未登錄的錯誤;
  • 項目中使用 vuex,axios,router;

判斷登錄方案需要滿足下面幾點:

  1. 未登錄狀態下的刷新:
    1.1 在需要登錄頁面中刷新是需要跳轉到登錄頁的;
    1.2 在不需要登錄的頁面中刷新,不需要跳轉;
  2. 在未登錄狀態下,跳轉到需要登錄頁面時,會直接跳轉到登錄頁;

先在路由文件里修改:

export default {
  path: '/person',
  component: person,
  name: 'person',
  redirect: 'person/index',
  meta:{
    requireLogin:true,
  },
  children: [
      //子頁面
    ]
  }

假如上面的代碼是一個用戶中心的路由,他是主頁面,其他都是他的子頁面,那么只需要在meta里添加requireLogin:true一次就行了,子頁面不需要修改什么;


在 main.js 里添加:

axios.interceptors.response.use(
    response => {
	  if(response.data.code === 500) {
        if (response.data.msg === '請先登錄') {
          router.push({
            path: '/login',
            query: {redirect: router.history.current.fullPath}
          })
          //如果需要可以在這里將 vuex 里的 user 改為空對象
        }
      //顯示錯誤信息
      return Promise.reject(response.data)
    }

    if(response.data.code === 0){
      return response;
    }
}, error => {
    //顯示錯誤信息
    return Promise.reject(error.response.data)
});


router.beforeEach((to, from, next) => {
  let user = router.app.$options.store.state.user;
  if (to.matched.some(record => record.meta.requireLogin)) {
    if (JSON.stringify(user) === '{}') {
      next();
      router.push({ path: '/login',query: { redirect: to.fullPath }})
    }else {
      next()
    }
  } else {
    next()
  }
});

根據 user 是否為一個空對象來判斷本地登錄狀態;


在 app.vue 里添加:

created(){
    this.$store.dispatch('getUser');
}

每一次刷新都會觸發該函數,作用是判斷登錄狀態和獲取最新的信息;


在 vuex/index 添加:

const store = new Vuex.Store({
    state: {
        user: JSON.parse(localStorage.user || '{}'),
    },
    mutations: {
        changeUser(state, msg){
            state.user = msg;
        },
    },
    actions: {
        getUser({commit}){
          axios.get(api.info).then(data => {
            commit('changeUser', data.data.member);//需根據實際修改
            localStorage.user = JSON.stringify(data.data.member || {});
          }).catch(err => {
            commit('changeUser', {});
            if (router.currentRoute.matched.some(record => record.meta.requireLogin)) {
              router.push({
                path: '/login',
                query: {redirect: router.currentRoute.fullPath}
              })
            }
          })
        },
    }
})

在某頁面下刷新,可以根據是否為需登錄頁面進行判斷,並且已登錄可以更新用戶信息;
用戶的信息都是存儲在 localStorage 里來成為默認值,但是 ajax 連接失敗的話,會變為空;

!!注意!!
上面的方法適用的是,不知道后台的登錄保存時間,然而,如果你知道后台的登錄狀態保存時間的話,我想可以有一種更好的方法,即 cookie
因為 cookie 會有一個保存的時間, 進入一個頁面判斷是否存在;
還可以使用 Web Workers ,在后台添加一個計時器,每一段時間判斷 cookie 是否存在,不過 cookie 能存儲的東西不多,還有 IE 對Web Workers 是不支持的,所以最好在 main 里判斷一下頁面是否對 web workers ;

放下我之前項目所用的登錄檢查方式:

let hasLogin = false // 是否登錄過
// 登錄攔截
router.beforeEach((to, from, next) => {
    if (document.cookie.includes('userName')) {
        hasLogin = true
        if (permission.indexOf(to.path) > -1) {
            next()
        } else {
            try {
                // 簡單的權限判斷
                let routesKey = Cookie.get('routesKey').split(',')
                let key = to.path.split('/')[1]
                if (routesKey.indexOf(key) > -1) {
                    next()
                } else {
                    next({path: '/'})
                }
            } catch (e) {
                next({path: '/login'})
            }
        }
    } else {
        if (to.path === '/login') { // 如果是登錄頁面路徑,就直接next()
            next()
        } else {
            if (hasLogin) {
                Cookie.clear('userName')
                ELEMENT.Message({
                    message: '登錄失效,請重新登錄!',
                    center: true,
                    type: 'warning'
                })
            }
            next({path: '/login', query: {redirect: to.fullPath}})
        }
    }
})

完;


免責聲明!

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



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