vue 页面长时间无操作自动退出系统(前端使用定时器定时发送请求token)

1、先判断用户是否是在登录页面进入系统的,如果是,则调取token定时器和点击事件

watch: {
    $route(to, from) {
      if (from.path == '/login') {
        this.moveEvent();
        this.isDon()
      }
    }
  },

2、如果用户一直处于操作的状态,token会有过期时间,采用定时器调取一下token,不会退出

	moveEvent() {
      clearInterval(this.timmer)
      this.timmer = setInterval(() => {
        this.refrenToken()
      }, 7 * 60 * 1000);
    },
    refrenToken(){
      userToken().then((res) => {
        if (res.data.code == 0) {
          sessionStorage.setItem("token",res.data.data.token)
        }
      });
    },

3、如果用户长时间无操作,则退出页面

isDon(){
      clearTimeout(this.logoutTime)
      // 30分钟无操作自动退出登录
      this.logoutTime = setTimeout(() => {
        this.goBack()
        if (this.$route.path != '/index' && this.$route.path != '/login') {
          this.$message({
              type: "error",
              message: "长时间无操作,退出登录。",
          });
        }
      }, 30 * 60 * 1000)
    },
    goBack () {
      sessionStorage.clear();
      localStorage.clear()
      clearInterval(this.timmer)
      clearTimeout(this.logoutTime)
      this.$router.push({path: '/index'})
    },

整体

<template>
  <div class="body" @mouseover="isDon" >
    <router-view></router-view>
  </div>
</template>
<script>
import { userToken } from "@/api/index"
export default {
  name: "app",
  data() {
    return {
      timmer: null,
      logoutTime: null
    }
  },
  watch: {
    $route(to, from) {
      if (from.path == '/login') {
        this.moveEvent();
        this.isDon()
      }
    }
  },
  created () {
    if (this.$route.params.id) {
      let permissionList = JSON.parse(sessionStorage.getItem('permissionList')).map(i => i.id)
      if (!permissionList.includes(Number(this.$route.params.id))) {
        this.goBack()
        this.$message({
          message: '您暂无该任务权限',
          type: "error",
        })
      }
    }
    this.moveEvent()
    this.isDon()
  },
  destroyed: function () {
    clearInterval(this.timmer)
    clearTimeout(this.logoutTime)
  },
  methods: {
    goBack () {
      sessionStorage.clear();
      localStorage.clear()
      this.$router.push({path: '/index'})
      clearInterval(this.timmer)
      clearTimeout(this.logoutTime)
    },
    isDon(){
      clearTimeout(this.logoutTime)
      // 30分钟无操作自动退出登录
      this.logoutTime = setTimeout(() => {
        this.goBack()
        if (this.$route.path != '/index' && this.$route.path != '/login') {
          this.$message({
              type: "error",
              message: "长时间无操作,退出登录。",
          });
        }
      }, 30 * 60 * 1000)
    },
    moveEvent() {
      clearInterval(this.timmer)
      this.timmer = setInterval(() => {
        this.refrenToken()
      }, 7 * 60 * 1000);
    },
    refrenToken(){
      userToken().then((res) => {
        if (res.data.code == 0) {
          sessionStorage.setItem("token",res.data.data.token)
        }
      });
    },
  }
};
</script>

你可能感兴趣的:(js,vue.js,javascript,前端)