需求
A端带参访问某一Java接口后跳转B端(中途自动登录),接口返回B端URL
实现思路
Java侧返回URL中带有用户ID或其他身份标识,B端在created之前处理URL并登录
访问Java接口数据
{
"user_id": "1",
"user_name": "admin",
"user_phone": "18812340001"
}
接口返回数据
{
"code": 200,
"msg": "SUCCESS",
"url": "http://localhost:8080/#/?userId=3"
}
/**
* 整个地址流转过程:
* @param 访问地址 http://localhost:8080/#/?userId=3
* 1、将访问地址存入 LocalStorage
* 2、将访问地址剪切为不带userId的地址,页面地址栏地址为(http://localhost:8080/#/)
* 3、页面刷新时将 LocalStorage 中存入的 访问地址取出,做刷新使用
* 4、页面刷新时,重复 步骤 1
*/
/**
* VUE生命周期,挂载之前
*/
beforeCreate() {
// 判断当前地址是否为带有 userId的地址,主要用于页面刷新时的地址变更
// 当页面刷新时,地址为不带userId的地址,会造成登录失败,页面会一直刷新
if(document.URL.indexOf('?') == -1) {
let currentUrl = getLocalStorage('userId');
// 所以将 LocalStorage 中的原地址(带有userId的地址)取出做为刷新后的地址
window.location.href = currentUrl.currentUrl;
}
},
created() {
this.getUserId();
// (方法省略)
this.login();
},
/**
* VUE生命周期,挂载完成
*/
mounted() {
// 将接口返回的地址存入 LocalStorage
setLocalStorage({'userId': window.location.href});
// 将当前地址剪切为不带userId的地址
window.location.href = document.URL.substring(0, document.URL.indexOf('?'));
},
/**
* 从地址中截取用户ID,做无感知登录使用
*/
getUserId() {
// 当前地址:http://localhost:8080/#/?userId=3
let currentUrl = document.URL;
// 截取ID http://localhost:8080/#/?userId=3 3
let userId = currentUrl.substring(currentUrl.indexOf('=') + 1);
// 登录账号的ID(省略)
this.account = userId;
},
/**
* 登录
*/
async login() {
// 获取用户ID
this.getUserId();
// 当用户ID 为空时,再次获取
if (!this.account) {
this.getUserId();
// 再次获取为空则返回,防止页面无限刷新
if (!this.account) {
return;
}
}
await authLoginByAccount({ userId: this.account })
.then(res => {
console.log('res--->', res)
// 登录后逻辑省略
// ...
});
}).catch(error => {
Toast.fail(error.data.errmsg);
});
}