vue+element 登錄超時自動退出

一、超時以後自動退出

//   APP.vue 
//   '/'是login頁面路由
<template>
  <div id="app">
    <router-view />
  </div>
</template>
<script>
let time = null //超時退出 定時器 必須放到全局,解決vue數據同步導致無法清除定時器
export default {
  name: "app",
  data() {
    return {
    }
  },
  methods: {
    currentTime(){ // 超時退出     
      if(time){
        window.clearTimeout(time)
        time = null
      }
      time = window.setTimeout(()=>{
        this.$message({
            message: '登錄超時,將返回登錄頁',
            type: 'error',
            duration: 1500
        })
        setTimeout(() => {
          //this.loginOut()
        }, 2000)
      },1000 * 60 * 30 * 4)
    },
  },
  created() {
    window.addEventListener('click', () => {
      if(this.$route.path != '/'){
        this.currentTime();
      }
    })
  },
};
</script>

二、超時以後用戶點擊、滾動後自動退出

//   APP.vue 
//   '/'是login頁面路由
<template>
  <div id="app">
    <router-view />
  </div>
</template>
<script>
let timmer = null //超時退出 定時器 必須放到全局,解決vue數據同步導致無法清除定時器
export default {
  name: "app",
  data() {
    return {
      lastTime:null,//超時退出 最後時間
    }
  },
  methods: {
    currentTime(){ // 超時退出     
       const currentTime = new Date();
       if (currentTime - this.lastTime > 1000 * 60 * 30 ) {
         this.lastTime = currentTime
         if (this.$route.path != '/') {
           this.$message({
               message: '登錄超時,將返回登錄頁',
               type: 'error',
               duration: 1500
           })
           setTimeout(() => {
             this.loginOut()
           }, 2000)
         }
       } else {
         this.lastTime = currentTime;
       }
    },
  },
  created() {
    //超時退出 start
    this.lastTime = new Date();
  
     window.addEventListener('resize', () => {
       if (timmer) {
         clearTimeout(timmer);
       }
       timmer = setTimeout(() => {
         if(this.$route.path != '/'){
	        this.currentTime();
	      }
       }, 3000)
     })

    window.addEventListener('click', () => {
      if (timmer) {
         clearTimeout(timmer);
       }
       timmer = setTimeout(() => {
         if(this.$route.path != '/'){
	        this.currentTime();
	      }
       }, 3000)
    })
      
     window.addEventListener('scroll', () => {
       if (timmer) {
         clearTimeout(timmer);
       }
       timmer = setTimeout(() => {
         if(this.$route.path != '/'){
	        this.currentTime();
	      }
       }, 3000)
     }, true)

     window.addEventListener('mousemove', () => {
       if (timmer) {
         clearTimeout(timmer);
       }
       timmer = setTimeout(() => {
         if(this.$route.path != '/'){
	        this.currentTime();
	      }
       }, 3000)
     }, true)
    //超時退出 end
  },
};
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章