需求
想要统计用户在页面停留的真实时间,进入页面开始计时,切出本页面后完毕,另外需要注意关闭浏览器网页窗口或者关闭整个浏览器也要停止计时。
代码实现
data() {
return {
browseTime: 0, // 浏览时长初始值为 0
clearTimeSet: null
}
},
mounted() {
window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
this.setBrowseTime() // 页面加载完成后开始计时
},
destroyed() {
window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))
clearInterval(this.clearTimeSet) // 离开页面后清除定时器
this.addBrowseRecord() // 上送后台接口,将浏览时长等信息传到后台,离开当前路由后调用
},
methods: {
addBrowseRecord() {
const payLoad = {
userId: this.userId,
deptId: this.depId,
browseTime: this.browseTime
}
addBrowseRecord(payLoad).then((res) => {
if (res.code === 0) {
console.log('保存停留时间成功', payLoad)
} else {
console.log('保存停留时间失败', payLoad)
}
}).finally(() => {
})
},
setBrowseTime() {
// 设置定时器
this.clearTimeSet = setInterval(() => {
this.browseTime++
console.log(this.browseTime, '时长累计')
}, 1000)
},
beforeunloadHandler(e) {
// 针对关闭窗口或者浏览器的
if (this.clearTimeSet != null) {
clearInterval(this.clearTimeSet)
this.addBrowseRecord()
}
console.log('关闭窗口之后')
}
}