vue 專案中處理使用者登入驗證以及會員等級的更新的記錄
阿新 • • 發佈:2018-11-21
最近用vue擼一個微信公眾號的專案,專案需要使用者登入,不登入是不開放頁面的,所以在main.js中用到了全域性的路由守衛
//main.js,使用者資訊分別儲存在本地localStorage和store中,作為長久儲存,只需一次登入 router.beforeEach(function (to, from, next) { if(!localStorage.getItem('userInfo') && to.path!='/authorization'){ //首次登入,或者本地個人資訊清除了 console.log('登入授權'); router.push({path:'/authorization'}) }else if(localStorage.getItem('userInfo') && !store.state.userInfo){ //已經登入授權,需要更新獲取使用者資訊 console.log('重新獲取使用者資訊'); store.dispatch('userInfo'); }else{ console.log('已經登入,也不需要獲取使用者資訊'); } /* 路由發生變化修改頁面title */ if (to.meta.title) { document.title = to.meta.title } next(); })
這樣的話,使用者只需要登入一次就可以了,當用戶的身份改變的時候,只需要刪除store中使用者的資訊,然後在actions中去重新獲取使用者的身份,並且更新本地localStorage中使用者的身份
userInfo:function(context){ var userInfo= JSON.parse(localStorage.getItem('userInfo')) || {}; getName({ username: userInfo.phone, access_token: userInfo.access_token, shop_type: 6, openid:userInfo.openid }).then(res=>{ console.log(res); if(res.data.status=='y'){ var group_id=res.data.result.group_id; var username=res.data.result.username; userInfo.member_group=group_id; userInfo.phone=username; context.commit('userInfo',userInfo); localStorage.setItem('userInfo',JSON.stringify(userInfo)); } }) }
不知道這樣子處理好不好,上面的路由守衛驗證登入也是在網上看了好多帖子,由於有一段時間了,地址也沒找到,在這裡做一個記錄