vue實(shí)現(xiàn)用戶長(zhǎng)時(shí)間不操作自動(dòng)退出登錄功能的實(shí)現(xiàn)代碼
一、需求說(shuō)明
昨天后端開(kāi)發(fā)人員讓我實(shí)現(xiàn)一個(gè)網(wǎng)頁(yè)鎖屏,當(dāng)時(shí)我一頭霧水,問(wèn)他為啥搞的跟安卓系統(tǒng)一樣。他的回復(fù)是'看起來(lái)帥點(diǎn)'。
首先我們梳理下邏輯,先來(lái)個(gè)簡(jiǎn)化版的,用戶長(zhǎng)時(shí)間未操作時(shí),返回登錄頁(yè)
二、思路
使用 mouseover 事件來(lái)監(jiān)測(cè)是否有用戶操作頁(yè)面,寫(xiě)一個(gè)定時(shí)器間隔特定時(shí)間檢測(cè)是否長(zhǎng)時(shí)間未操作頁(yè)面,如果是,退出登陸,清除token,返回登錄頁(yè)
三、實(shí)現(xiàn)
【1】在util文件夾下創(chuàng)建一個(gè)storage.js封裝localStorage方法
export default { setItem(key, value) { value = JSON.stringify(value); window.localStorage.setItem(key, value) }, getItem(key, defaultValue) { let value = window.localStorage.getItem(key) try { value = JSON.parse(value); } catch {} return value || defaultValue }, removeItem(key) { window.localStorage.removeItem(key) }, clear() { window.localStorage.clear() },}
【2】在util文件夾下創(chuàng)建一個(gè)astrict.js
每隔30s去檢查一下用戶是否過(guò)了30分鐘未操作頁(yè)面
// 引入路由和storage工具函數(shù)import storage from ’@/utils/storage’import router from '@/common/router'let lastTime = new Date().getTime()let currentTime = new Date().getTime()let timeOut = 30 * 60 * 1000 //設(shè)置超時(shí)時(shí)間: 30分鐘window.onload = function () { window.document.onmousedown = function () { stroage.setItem('lastTime', new Date().getTime()) }};function checkTimeout() { currentTime = new Date().getTime()//更新當(dāng)前時(shí)間 lastTime = stroage.getItem('lastTime'); if (currentTime - lastTime > timeOut) { //判斷是否超時(shí) // 清除storage的數(shù)據(jù)(登陸信息和token) storage.clear() // 跳到登陸頁(yè) if(router.currentRouter.name == ’login’) return // 當(dāng)前已經(jīng)是登陸頁(yè)時(shí)不做跳轉(zhuǎn) router.push({ name: ’login’ }) }}export default function () { /* 定時(shí)器 間隔30秒檢測(cè)是否長(zhǎng)時(shí)間未操作頁(yè)面 */ window.setInterval(checkTimeout, 30000);}
【2】在main.js引入astrict.js
import Astrict from ’@/utils/astrict’Vue.use(Astrict)
四、鎖屏
實(shí)現(xiàn)網(wǎng)頁(yè)鎖屏的思路和上面自動(dòng)退出登錄類似,稍微改動(dòng)實(shí)現(xiàn)如下:
【1】用戶長(zhǎng)時(shí)間未操作,彈出設(shè)置鎖屏密碼彈框設(shè)置鎖屏密碼
【2】密碼(password)和鎖屏狀態(tài)(isLock)存入localStorage 和vuex
【3】設(shè)置成功后跳轉(zhuǎn)到鎖屏登錄頁(yè)
【4】 在路由里面判斷vuex里面的isLock(為true鎖屏狀態(tài)不能讓用戶后退url和自行修改url跳轉(zhuǎn)頁(yè)面否則可以)
【5】用戶在鎖屏登錄頁(yè)輸入剛剛設(shè)置的鎖屏密碼,即可解開(kāi)鎖屏
總結(jié)
到此這篇關(guān)于vue實(shí)現(xiàn)用戶長(zhǎng)時(shí)間不操作自動(dòng)退出登錄功能的實(shí)現(xiàn)代碼的文章就介紹到這了,更多相關(guān)vue 長(zhǎng)時(shí)間不操作自動(dòng)退出登錄內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 在Android中使用WebSocket實(shí)現(xiàn)消息通信的方法詳解2. 淺談python出錯(cuò)時(shí)traceback的解讀3. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向4. Python importlib動(dòng)態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼5. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無(wú)效問(wèn)題6. 利用promise及參數(shù)解構(gòu)封裝ajax請(qǐng)求的方法7. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解8. .NET中l(wèi)ambda表達(dá)式合并問(wèn)題及解決方法9. JSP數(shù)據(jù)交互實(shí)現(xiàn)過(guò)程解析10. Nginx+php配置文件及原理解析
