效果如下:
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; width: 100%; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; min-width: 1200px; /* min-height: 800px; */ } </style>
可以在vue項目下的app.vue文件中來進行設置,原理是通過定時器一秒執行一次,然后比較當前時間與最后點擊時間之差,若是大於設置的超時時間,則退出登錄,彈出提醒。
其中涉及到一個問題,若是在退出登錄之后,最后點擊時間由於未改變,還是之前的時間,所以定時器執行的時候,兩者之差一直是大於超時時間的,因此可以進行判斷,用戶若是登錄狀態,則退出登錄;否則的話,可以更新最后點擊時間為當前時間,這樣,登錄進去之后用戶的最后點擊時間即為初始值,即登陸進來的時間、當前時間。
此時,就可完美實現啦。