步驟一、寫js方法
寫js方法并暴露出去
export function isOperateFun() {}
核心邏輯:記錄當(dāng)前時間,更新每次操作時的時間,計算:當(dāng)前時間- 最后操作時間 > 限定時間,如果大于就是長時間未操作
這個js方法會在頁面加載成功后就執(zhí)行,故需要一開始就加載定時器,而后每次觸發(fā)事件后清除原來的定時器并重新開始
// 用戶長時間未操作 退出登錄
import store from '@/store'
import router from '@/router'
var timer = null
clearInterval(timer)
export function isOperateFun() {
var lastTime = new Date().getTime() // 最后一次點(diǎn)擊時間
var currentTime = new Date().getTime() // 當(dāng)前時間
var timeOut = 66 * 1000 // 允許最長未操作時間
var i = 1 // 輔助作用
function handleReset() { // 重新賦值最后一次點(diǎn)擊時間,清除定時器,重新開始定時器
// console.log('又點(diǎn)擊了!?。。。?!')
i = 1
lastTime = new Date().getTime()
if (timer) {
clearInterval(timer)
timer = null
}
if (!timer) {
// console.log('真好!重新開始')
handleInterval()
}
}
document.onclick = () => { // 單擊事件
handleReset()
}
document.ondblclick = () => { // 雙擊事件
handleReset()
}
document.onmousedown = () => { // 按下鼠標(biāo)鍵時觸發(fā)
handleReset()
}
document.onmouseup = () => { // 釋放按下的鼠標(biāo)鍵時觸發(fā)
handleReset()
}
document.onmousemove = () => { // 鼠標(biāo)移動事件
handleReset()
}
document.onmouseover = () => { // 移入事件
handleReset()
}
document.onmouseout = () => { // 移出事件
handleReset()
}
document.onmouseenter = () => { // 移入事件
handleReset()
}
document.onmouseleave = () => { // 移出事件
handleReset()
}
function handleInterval() { // 定時器
timer = setInterval(() => {
currentTime = new Date().getTime() // 當(dāng)前時間
console.log(`${i++}-currentTime`, currentTime)
console.log('最后一次點(diǎn)擊時間', lastTime)
if (currentTime - lastTime > timeOut) {
console.log('長時間未操作')
clearInterval(timer) // 清除定時器
store.dispatch('user/logout').then(() => { // 執(zhí)行退出并跳轉(zhuǎn)到首頁
const path = window.location.href.split('#')[1]
if (path !== '/home') { // 判斷當(dāng)前路由不是首頁 則跳轉(zhuǎn)至首頁
router.push('/home')
}
window.AndroidWebView.loginOut() // 執(zhí)行安卓退出方法
})
}
}, 1000)
}
handleInterval() // 一開始程序 默認(rèn)執(zhí)行定制器
}
步驟二、在app.vue中調(diào)用js方法
引入外部js方法import { isOperateFun } from '@/utils/isOperate.js'
執(zhí)行方法isOperateFun()
<script>
import { isOperateFun } from '@/utils/isOperate.js'
export default {
data() {
return {
}
},
created() {
isOperateFun()
},
methods: {
}
}
</script>