之前探讨过这个问题,其实这个方案使用vuex存储定时器就好了。这样就能保证所有页面使用同一个定时器变量,而且在开启下一个定时器之前,可以很方便的关闭上一个定时器
废话不多说,先说逻辑。
逻辑
1、将定时器变量存储在vuex中,每次启动下一个前先关闭上一个
2、操作包括页面任意屏幕点击,触摸滑动,以及其他认为需要关闭定时器的操作,比如笔者项目中就在调起摄像头时需要关闭定时器,结束后重新开启定时器
3、页面初始化时也要启动定时器
vuex
那么我们先在vuex中创建变量函数存储,更新定时器。
state.js
export default{
clearTimeOut:null,//20s无操作的timeOut
}
mutation-type.js
export const SET_CLEAR_TIME_OUT = "SET_CLEAR_TIME_OUT" // 20s无操作的timeOut
action.js
import {SET_CLEAR_TIME_OUT} from './mutation.type'
export default{
/**
* 20s无操作的timeOut
* @param commit
* @param clearTimeOut
* @param state
*/
setClearTimeOut({commit,state}, clearTimeOut) {
window.clearTimeout(state.clearTimeOut)
// console.log('设置timeout',clearTimeOut)
commit(SET_CLEAR_TIME_OUT,clearTimeOut)
},
}
mutation.js
import {SET_CLEAR_TIME_OUT} from './mutation.type'
[SET_CLEAR_TIME_OUT](state,clearTimeOut) { //20s无操作的timeOut
state.clearTimeOut = clearTimeOut
},
clear.js
因为有许多页面需要使用,而且大部分逻辑相同。因此我们在mixins文件夹里面创建clear.js混入文件
clear.js
export default {
data(){
return{
delayTime:20000,//延迟时间
}
},
created() {
this.screenClick()
},
methods:{
/**
* 屏幕在点击
*/
screenClick(){
// console.log('屏幕点击')
this.delayUserHandle()
},
/**
* 延迟
*/
delayUserHandle(){
this.$store.dispatch('setClearTimeOut',null)
// console.log('开始延迟',this.$route.name)
let timeOut = window.setTimeout(()=> {
// console.log('延迟结束',this.$route.name)
this.$store.dispatch('setClearTimeOut',null)
const {name} = this.$route
if(['Home','Admin',].includes(name)){
//以防万一,排除不需要执行的页面,不做处理
return
}
this.$store.dispatch('logout')
this.$router.replace('/')
},this.delayTime)
// console.log(this.delayTime)
this.$store.dispatch('setClearTimeOut',timeOut)
},
/**
* 触摸开始
*/
touchStart(){
this.$store.dispatch('setClearTimeOut',null)
},
/**
* 触摸滑动
*/
touchmove(){
this.$store.dispatch('setClearTimeOut',null)
},
/**
* 触摸结束
*/
touchEnd(e){
// console.log('touchEnd')
//console.log(e)
// console.log(this.$route.name)
this.delayUserHandle()
}
},
}
使用
使用就很简单了,这里以home页面为例
<template>
<div class="home" @click="goLogin" @touchmove="touchmove" @touchstart="touchStart" @touchend="touchEnd">
首页内容
</div>
</template>
<script>
import clear from '../mixins/clear'
export default {
name: 'Home',
mixins:[clear],
}
</script>
需要注意的是,如果你在页面上的某个按钮点击时不希望重置定时器,那就加上.stop修饰符,阻止事件冒泡即可。需要在别的事件里触发定时器,那就直接调用 this.delayUserHandle()
网友评论