1. 程式人生 > >vue+vue-cookie 微信授權登入

vue+vue-cookie 微信授權登入

 

 

 

基本實現思路是:

  • 無論使用哪個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');
			}
			
}

基本就是這三步,搞定微信授權登入,此文章只是自己記錄 ,不喜勿噴!