vue 检查登录的接口,在页面登录跳转后会再次请求 造成了死循环?
我有一个检查登录接口checked/login
要求必须放在App.vue页面
在mounted
方法中我请求了检查登录接口,
在打开登录页面/web/login
时会调用一次,正常登录后 后台返回的字段data
let data = { errcode: 0,
is_login: true,
isAdmin: false,
msg: "获取成功",
info: {status: 4}
}
根据 data.info.status === 4
判断跳转到/web/index
页面,
但是在/web/index
页面也会请求一次checked/login
接口,然后会再次根据 data.info.status === 4
判断跳转到/web/index
页面,这样就陷入了一个一直刷新的局面,该怎么解决???
回答:
用路由守卫
router.beforeEach((to, from, next) => { if (to.path !== '/web/login') {
// 检查登录状态
axios.post('checked/login').then(response => {
let data = response.data;
if (data.info.status === 4) {
next('/web/index');
} else {
next();
}
});
} else {
next();
}
});
检查当前路由:
mounted() { if (this.$route.path !== '/web/index') {
// 请求检查登录接口
axios.post('checked/login').then(response => {
let data = response.data;
if (data.info.status === 4) {
this.$router.push('/web/index');
}
});
}
}
回答:
- 既然
app.vue
已经调用一次checked/login
,/web/login
为什么还要调用呢? - 可以在
app.vue
调用checked/login
之后status==4
之后, 跳转到/web/login
时携带参数或者在sessionStorage
里面存储flag, 在/web/login
获取flag, 如果存在就不调用checked/login
了
回答:
在请求成功后,将获取到 key 或者状态保存到 sessionStorage 里,然后更改 App.vue onMounted 里请求到逻辑。
if(sessionStorage.isLogin){//请求函数
fetchData()
}
以上是 vue 检查登录的接口,在页面登录跳转后会再次请求 造成了死循环? 的全部内容, 来源链接: utcz.com/p/934897.html