vue实现页面停留时长
Vue 实现页面停留时长统计
使用生命周期钩子和计时器
在 Vue 组件中,可以通过 mounted 和 beforeDestroy 钩子来记录页面的进入和离开时间。创建一个计时器来计算停留时长。
export default {
data() {
return {
enterTime: null,
leaveTime: null,
duration: 0,
timer: null
}
},
mounted() {
this.enterTime = new Date()
this.timer = setInterval(() => {
this.duration = Math.floor((new Date() - this.enterTime) / 1000)
}, 1000)
},
beforeDestroy() {
clearInterval(this.timer)
this.leaveTime = new Date()
const totalDuration = Math.floor((this.leaveTime - this.enterTime) / 1000)
console.log(`页面停留时长:${totalDuration}秒`)
}
}
使用路由守卫全局统计
在 Vue Router 的全局守卫中统计页面停留时长,适用于需要全局监控的场景。
import router from './router'
let startTime
router.beforeEach((to, from, next) => {
if (from.name) {
const endTime = new Date()
const duration = Math.floor((endTime - startTime) / 1000)
console.log(`从 ${from.name} 离开,停留时长:${duration}秒`)
}
startTime = new Date()
next()
})
结合本地存储或 API 上报
将停留时长数据保存到本地存储或通过 API 上报到服务器,便于后续分析。
export default {
methods: {
reportDuration(duration) {
localStorage.setItem('last_page_duration', duration)
// 或调用 API 上报
// axios.post('/api/track', { duration })
}
},
beforeDestroy() {
const totalDuration = Math.floor((new Date() - this.enterTime) / 1000)
this.reportDuration(totalDuration)
}
}
使用第三方库
如果需要更复杂的功能,可以考虑使用专门的用户行为分析库,如 vue-analytics 或 matomo。
import VueAnalytics from 'vue-analytics'
Vue.use(VueAnalytics, {
id: 'UA-XXX-X',
router
})
通过以上方法,可以灵活地实现页面停留时长的统计和上报。







