可以把这个功能直接写进需要这个功能的.vue文件中,但最好把功能变成一个单独的js文件抽出去。代码中用到了vuex。
uniapp:
uniapp主要设计小程序和app,所以并不需要检测键盘以及鼠标移动,只要检测有没有点击事件就可以了。
js代码:
//引用vuex
import store from '../store/index.js';
export const timeOut = () => {
// 上一次点击时间
let lastTime = null
// 当前时间
let currentTime = null
// 超时时间【可以自己设置】
let sys_timeout = 5 * 60 * 1000
// 每隔多长时间检查是否超时【可以自己设置】
let check_time = 5 * 60 * 1000
// 计时器【此为功能实现的方法,现在为空】
let goOut = null
const isTimeOut = () => {
// 页面上一次的点击时间
lastTime = store.state.lastTime
currentTime = new Date().getTime()
// 超时了
if((currentTime - lastTime) > sys_timeout) {
return true;
} else {
return false;
}
}
const isLoginOut = () => {
clearInterval(goOut);
//setInterval方法来确定多长时间检测一次有没有超时
goOut = setInterval(() => {
// 判断一下是否超时,如果超时了就退出
if (isTimeOut()) {
// 需要转到的页面【这里用你自己的跳转方法和地址】
uni.reLaunch({
url: `/pages/index/index`,
});
//已经超时跳转到相应界面,不需要计时了
clearInterval(goOut)
}else {
}
}, check_time);
}
isLoginOut();
}
vuex的index代码:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
// 记录最后一次点击时间的元素
lastTime:new Date().getTime(),
},
mutations: {
//点击事件调用,刷新最后一次点击时间
lastTimeUpdata: (state, lastTime) => {
state.lastTime = lastTime;
}
},
actions: {}
})
export default store
前端代码:
<template>
<view class="content" @click="updataClickTime">
</view>
</template>
<script>
import {timeOut} from '../../until/timeout.js'
export default {,
onShow(){
// 启动定时器
timeOut();
},
methods:{
// 记录点击时间,传入参数为当前时间
updataClickTime(){
this.$store.commit('lastTimeUpdata',new Date().getTime())
},
},
</script>
<style>
page{
.content {
width:900rpx;
height:900rpx;
background-color: pink;
}
</style>
思路:给前端某区域设置点击事件,每次点击上传最后点击时间。前端生命周期函数触发外部js计时器。每隔多长时间计时器计算当前时间减最后一次点击事件来测试是否超时。