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');
			}
			
}

基本就是这三步,搞定微信授权登录,此文章只是自己记录 ,不喜勿喷!

 

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