即使在 Vuejs 中刷新页面后,如何保持登录会话处于活动状态?

时间:2021-06-01 14:02:01

标签: javascript vue.js local-storage commercetools

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>

使用我的登录凭据成功登录后,我可以重定向到某个页面,如果我单击注销,我将成功注销,但问题是即使登录后没有单击注销按钮,即使我刷新了我的它正在注销的页面。

1 个答案:

答案 0 :(得分:1)

尝试在本地/会话存储中设置访问令牌,然后在每次加载页面时检查它是否存在。

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