vue实现登录之后长时间未操作,退出登录

效果如下:

vue实现用户登录系统之后,长时间未操作,提示登录超时,直接退出登录,跳转至登录页面。

app.vue:

<template>
  <div id="app" @click="clicked">
    <router-view/>
  </div>
</template>
<script>
import {mapActions } from 'vuex';
import store from './store';
export default {
  name: 'app',
  data (){
    return {
        lTime: new Date().getTime(), // 最后一次点击的时间
        cTime: new Date().getTime(), //当前时间
        // tOut: 60 * 10 * 1000,   //超时时间10min
        tOut: 5 * 1000,
        t1: ''
    } 
  },
  mounted () {
    this.t1 = setInterval(this.tTime, 1000);
  },
  methods:{
    clicked () {
      this.lTime = new Date().getTime()  //当界面被点击更新点击时间
    },
    tTime() {
      this.cTime = new Date().getTime();
      if (this.cTime -this.lTime > this.tOut) {
        //未登录状态
        if(localStorage.getItem('loginname') == undefined){
          this.lTime = new Date().getTime();
        }else{
          this.FedLogOut();
          this.$alert('登录超时,请重新登录', '提示', {
            confirmButtonText: '确定'
          });
        }
      }
    },
    // 退出登录点击事件
    ...mapActions([
      'FedLogOut',
    ]),
    
  },
}
</script>

<style>
@import "./assets/css/common.scss"; /*引入公共样式*/
#app {
    position: absolute;
    top:0;
    bottom: 0;
     100%;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
  min- 1200px;
  /* min-height: 800px; */
}
</style>

可以在vue项目下的app.vue文件中来进行设置,原理是通过定时器一秒执行一次,然后比较当前时间与最后点击时间之差,若是大于设置的超时时间,则退出登录,弹出提醒。

其中涉及到一个问题,若是在退出登录之后,最后点击时间由于未改变,还是之前的时间,所以定时器执行的时候,两者之差一直是大于超时时间的,因此可以进行判断,用户若是登录状态,则退出登录;否则的话,可以更新最后点击时间为当前时间,这样,登录进去之后用户的最后点击时间即为初始值,即登陆进来的时间、当前时间。

此时,就可完美实现啦。

原文地址:https://www.cnblogs.com/5201314m/p/11347214.html