先贴代码,有时间在解释
html
<template>
<div :class="$style.root">
<div>主页面</div>
<el-input v-model="txt" @input="onChange" />
</div>
</template>
<script>
const TIME = 10; //时间,用于限定多长时间无操作提醒
export default {
data() {
return {
txt: 1,
worker: null,
};
},
mounted() {
this.worker = new Worker('/worker.js');
this.worker.postMessage('start');
this.worker.addEventListener('message', e => {
console.log('e: ', e.data);
const { times } = e.data;
if (times >= TIME) {
this.$message.error('页面失效');
// 结束通信
this.worker.postMessage('end');
}
});
document.addEventListener('visibilitychange', function () {
if (document.visibilityState == 'visible') {
console.log('页面已显示');
} else if (document.visibilityState == 'hidden') {
console.log('页面已隐藏');
}
});
},
methods: {
onChange() {
this.worker.postMessage('end');
this.worker.postMessage('start');
},
},
};
</script>
<style lang="scss" module>
@import '../../styles/common';
.root {
@include center;
}
</style>
// public下面的worker.js
javascript
let timer;
self.addEventListener('message', e => {
let times = 0;
let msg;
if (e.data == 'start') {
timer = setInterval(() => {
times++;
msg = {
status: 'editing',
times,
};
self.postMessage(msg);
}, 1 * 1000);
} else {
times=0;
clearInterval(timer);
}
});