实现步骤:
1.在响应拦截器跳转时添加参数
window.location.href = '#/login?returuurl=' + window.location.hash.substr(1)
2.在登录成功时判断是否携带参数,是则返回传参页
应用场景:用户浏览页面需要进行登录时,为避免找不回浏览记录,在登录后返回登录前浏览的页面。
响应拦截器
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
// console.log(response);
if (response.data.statusCode == 401 || response.data.statusCode == 403) {
Toast.fail(response.data.message)
console.log(window.location.hash);// #/articleDetail/1
console.log(window.location.hash.substr(1));// /articleDetail/1
// 拿到哈希值,截取需要的部分传入url
//returuurl:代表键,参数是?后面键=值
window.location.href = '#/login?returuurl=' + window.location.hash.substr(1)
}
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
跳转成功后url效果
登录页
console.log(window.location.hash); // 哈希值: #/login?returuurl=%2FarticleDetail%2F10
console.log(window.location.hash.split("=")[1]); // 截取需要的哈希值: %2FarticleDetail%2F10
console.log(decodeURIComponent(window.location.hash.split("=")[1])); // 解码后: /articleDetail/10
let url = decodeURIComponent(window.location.hash.split("=")[1]);
if (url && url != "undefined") {
this.$router.push({ path: url });
} else {
this.$router.push({ path: `/personal/${res.data.data.user.id}` });
}
}