javascript - 即使在 Vuejs 中刷新页面后,如何保持登录会话处于活动状态?
问题描述
signInMe() {
this.$store.dispatch('setLoggedUser', true);
this.$store.dispatch('setGenericAccessToken', response.data.access_token);
this.errorMessage = "";
}, (error) => {
if (error) {
this.errorMessage = error.response.data.message;
this.isLoginFailed = true;
this.emailFailureCount = this.emailFailureCount + 1;
}
}).catch(error => {})
},
logout() {
localStorage.clear();
localStorage.setItem('userType', "G");
this.$store.dispatch('setLoggedUser', false);
this.$store.dispatch('setAccessToken', '');
this.$router.push('/')
this.registeredUser = false;
},
<div class="myprofileroute" @click="logout">Logout</div>
使用我的登录凭据成功登录后,我可以重定向到某个页面,如果我点击注销,我将成功注销,但问题是即使在登录后没有点击注销按钮,即使我刷新我的页面也是如此退出。
解决方案
尝试在本地/会话存储中设置访问令牌,然后在每个页面加载时检查它是否存在。
async login(){
try{
const userData = await axios.post('yourapi');
const token = userData.access_token;
localStorage.setItem('userData', userData);
localStorage.setItem('accessToken', token);
this.$router.push('/dashboard');
}catch(err){
//Handle errors
}
}
然后可能在您的主布局或 Vue 实例上
mounted(){
const userData = localStorage.getItem('userData');
const accessToken = localStorage.getItem('accessToken');
localStorage.setItem('userType', "G");
this.$store.dispatch('setLoggedUser', userData);
this.$store.dispatch('setAccessToken', accessToken);
}
推荐阅读
- javascript - 如何从输入中获取多个字符串并将它们放入同一个数组中?
- python - 在 matplotlib 中交互式变形多边形
- javascript - 在 next.js 中,多分区的意义何在
- jquery - 拖动和点单击时的猫头鹰轮播滑块不起作用
- javascript - react.js 中的承诺响应后如何更新状态
- asp.net - 通过 NuGet 安装后,是否有更简单的方法可以在母版页中引用 Bootstrap 文件?
- javascript - 在反应组件中使用异步等待
- mongodb - 使用聚合查询从嵌套数组 mongo 中的每个元素返回展平数组
- laravel - Laravel:将输入查询的结果更改为友好的 url
- xaml - 如何将运行时类中的数组绑定到 ListView?