最開始想做成一個公共的,完全提取出來的一個組件,組件設置背景透明,到時候哪個頁面需要,直接引入組件就可以了,所以最開始做的是一個vue的組件,在組件中,監聽頁面的@touchstart,但是這個組件會蓋住原來頁面的一些操作,導致原來頁面的操作無法進行,所以最后只是把公共的方法提取出來做了mixins,然后在原來的頁面加了@touchstart.capture,為啥要capture,下面會具體描述。
mixins代碼:
import {timeOutToHome} from "@/static/constant/patient.js"
import {pageReLauncho } from '@/utils/common';export default {data() {return {idleTimer: null, // 定時器};},methods: {// 啟動定時器startIdleTimer() {this.idleTimer = setTimeout(() => {// 檢查當前頁面是否仍然活躍:因為剛開始,是dragPatient中的click先觸發,然后頁面的click再觸發,導致先跳轉頁面,才執行重置定時器,跳轉頁面后,有執行定時器跳到首頁了,現在在頁面外層的click增加了click.capture,就是先執行外層click-重置定時其,在執行dragPatient的click,就不會有問題// const pages = getCurrentPages();// const currentPage = pages[pages.length - 1];// console.log('-----current', currentPage.route)// if (currentPage.route !== "pages/patient/patient") {// this.clear() // 如果已經不是當前頁面,清理定時器// return;// }console.log('----當前播放狀態', this.playStatus)if(!this.playStatus){console.log("頁面長時間無操作,執行特定事件");this.onIdle();}}, timeOutToHome);},// 重置定時器resetIdleTimer() {console.log('---重置定時器')this.clear()this.startIdleTimer();},// 頁面無操作時執行的事件onIdle() {// 在這里執行你想要的操作:例如:彈出提示框、跳轉頁面等console.log("用戶長時間沒有操作頁面");pageReLauncho("index/home")},// 監聽用戶操作handleUserActivity() {this.resetIdleTimer();},clear(){clearTimeout(this.idleTimer);this.idleTimer = null}},onShow() {// 頁面加載時啟動定時器this.startIdleTimer();},onHide() {console.log('---clear timeout')this.clear()},onUnload() {console.log('---clear timeout')this.clear()}
};
主頁面代碼:
<template><view class="patient-home-container" @touchstart.capture="handleUserActivity">
注意點分析:
1、測試的時候,頁面有個側邊導航,點擊跳轉其他頁面,但是跳到其他頁面過了一段時間,又跳到首頁了,檢查后發現,原來側邊導航的點擊在頁面點擊之前執行了,導致即使跳轉頁面,還會執行每隔一段時間跳轉首頁,加上capture后,就會先執行頁面的操作,在執行頁面內按鈕的操作,具體如下圖
2、之前把touchStart放在了組件中,但是會導致頁面的click失效,所以放回了頁面中。
3、這里面mixins多了一個操作,判斷視頻是否播放,因為需求:如果視頻正在播放不允許返回首頁,所以在mixins中判斷了當前視頻播放的狀態,這個狀態在頁面中通過播放、暫停等事件控制,主要代碼如下:
<video ref="myVideoRef"class="video-player" :src="currentVideo" :poster="currentPoster"@play="onPlay"@pause="onPause"@ended="onEnded"controls>
</video>onPlay(e) {console.log('視頻開始播放', e);this.playStatus = true;
},
onPause(e) {console.log('視頻暫停', e);this.playStatus = false;this.resetIdleTimer()
},
onEnded(e) {console.log('視頻播放結束', e);this.playStatus = false;this.resetIdleTimer()
},