vue实现页面停留时长
实现页面停留时长统计的方法
在Vue中实现页面停留时长统计,可以通过生命周期钩子和浏览器API结合实现。以下是几种常见的方法:
使用生命周期钩子和Date对象
在组件的created或mounted钩子中记录进入时间,在beforeDestroy或beforeUnmount钩子中计算停留时长并发送统计请求。
export default {
data() {
return {
enterTime: null
}
},
mounted() {
this.enterTime = new Date()
},
beforeUnmount() {
const leaveTime = new Date()
const duration = leaveTime - this.enterTime
// 发送统计请求
this.sendAnalytics(duration)
},
methods: {
sendAnalytics(duration) {
// 使用fetch或axios发送数据到后端
console.log(`页面停留时长: ${duration}ms`)
}
}
}
使用window.performance API
浏览器提供的Performance API可以更精确地测量页面性能和时间。
export default {
mounted() {
window.performance.mark('pageEnter')
},
beforeUnmount() {
window.performance.mark('pageLeave')
window.performance.measure('pageStay', 'pageEnter', 'pageLeave')
const measures = window.performance.getEntriesByName('pageStay')
const duration = measures[0].duration
this.sendAnalytics(duration)
}
}
使用路由守卫全局统计 对于SPA应用,可以在全局路由守卫中实现全站页面停留统计。
// router.js
let startTime
router.beforeEach((to, from, next) => {
if (from.name) {
const endTime = Date.now()
const duration = endTime - startTime
console.log(`停留在${from.name}时长: ${duration}ms`)
// 发送统计
}
startTime = Date.now()
next()
})
注意事项
- 对于单页应用,需要考虑路由切换时的统计
- 用户最小化窗口或切换标签页时需要特殊处理
- 生产环境应该将数据发送到后端存储,而非仅console.log
- 考虑用户隐私和GDPR等数据保护法规
以上方法可以根据实际需求选择或组合使用,实现精确的页面停留时长统计功能。







