基本實現思路是:
- 無論使用哪個url進入網站都會先觸發router.beforeEach鉤子
- 在router.beforeEach鉤子中判斷用戶當前登錄狀態
- 若沒有登錄則保存用戶進入的url並跳轉到login授權頁面
- login授權頁面完成微信授權以及isLogin(用戶登錄狀態)的寫入實現用戶登錄
- 獲取前面保存的用戶進入url並跳轉
1、首先安裝 vue-cookie (或者直接用locaStorage/sessionStorage)
npm install vue-cookies --save
然後在mai.js全局引入
//導入cookies
import VueCookies from 'vue-cookies'
Vue.use(VueCookies)
import VueCookies from 'vue-cookies'
Vue.use(VueCookies)
2、更改router/index.js
//導入cookies
import VueCookies from 'vue-cookies'
Vue.use(VueCookies)
在路由裏綁定login.vue 授權頁面
routes: [
//授權
{
path: '/login',
name: 'login',
component: resolve => require(['../page/login/login.vue'], resolve),
meta: {title: '授權'}
},
]
router.beforeEach
註冊一個全局前置守衛
vueRouter.beforeEach((to, from, next) => {
// 第一次進入項目
let isLogin = VueCookies.get('isLogin');
var code = util.util.prototype.getQueryString('code');
//未登錄,並且進入地址不是登錄頁
if (!isLogin && to.path != "/login") {
VueCookies.set("beforeLoginUrl", to.fullPath,60*60*1); // 保存用戶進入的url
next("/login");
return false;
}
//已登錄,並且有code返回
else if(isLogin && code != null && to.path == "/login") {
next("/login");
return false;
}
next();
});
3、設置login.vue授權頁面
login的方法是獲取後臺微信授權登錄地址跳轉的
methods: {
//用戶登錄授權 這裏是請求後臺獲取微信授權登錄地址跳轉
login:function(){
var that = this;
var skipUrl = window.location.protocol +'//'+window.location.host+'/#/login';
that.Request.login(skipUrl)
.then(res =>{
if(res.code == 0){
console.log(res.data)
window.location.href=res.data;
}
})
},
},
created() {
//獲取登錄回來的code
var code = this.util.getQueryString('code');
//判斷當前url中有沒有 code
//未登錄,而且沒有code的情況下
if(this.$cookies.get('isLogin') == null && code == null){
//跳轉微信登錄
this.login();
}
//未登錄,有code
else{
//存儲登錄狀態 (1小時過期)
this.$cookies.set('isLogin',true,60*60*1);
//獲取beforeLoginUrl,我們的前端頁面
let url = this.$cookies.get('beforeLoginUrl');
console.log('跳轉地址'+url)
//跳轉
this.$router.push({path:url})
//刪除 cookie中beforeLoginUrl
this.$cookies.remove('beforeLoginUrl');
}
}
基本就是這三步,搞定微信授權登錄,此文章只是自己記錄 ,不喜勿噴!