本项目使用vue-cookies存储用户信息(vue-session同理),在检测到用户无操作5分钟后调用logout函数进行用户登出操作。

部分函数使用Element-UI的接口,如this.$confirm等。

// App.vue
<template>
  <div id="app">
    <router-view/>
  </div>
</template>

<script>
export default {
  data() {
    return {
      logoutLimit: 1000 * 60 * 5, // 5分钟
    }
  },

  mounted() {
    // 超时登出
    let logoutTimer = setTimeout(this.logout, this.logoutLimit);
  
    let userOpDelay = () => {
      clearTimeout(logoutTimer);
      logoutTimer = setTimeout(this.logout, this.logoutLimit);
    }

    document.getElementById("app").addEventListener('keydown', function(e){ userOpDelay(); });
    document.getElementById("app").addEventListener('mousemove', function(e){ userOpDelay(); });
    document.getElementById("app").addEventListener('mousedown', function(e){ userOpDelay(); });
    document.getElementById("app").addEventListener('click', function(e){ userOpDelay(); });
    document.getElementById("app").addEventListener('scroll', function(e){ userOpDelay(); });
  },

  methods: {
    logout() {
      if (this.$cookies && this.$cookies.get("token") && this.$cookies.get("token") != "") {
        this.axios.get(`api/user/logout?token=${this.$cookies.get("token")}`).then(
          (res) => {
            let response = res.data;
            if (!response.errorCode) {
              this.$confirm('检测到最近无任何操作,账户自动登出。请重新登录!', '提示', {
                confirmButtonText: '确定',
                showCancelButton: false,
                type: 'warning'
              }).then(() => {
                this.$cookies.remove("token");
                this.$router.push({
                  name: "login"
                });
              }).catch(() => {
  
              }); 
            } else {
              this.$message({
                message: "登出失败",
                type: "error"
              });
            }
          }
        ).catch(
          (error) => {
            this.$message({
              message: error,
              type: "error"
            });
          }
        )
      }
    }
  }
}
</script>
Logo

前往低代码交流专区

更多推荐