前端如何配合后端埋点
需求:点击按钮时和进入离开页面时,监听用户行为
思路: 监听点击事件,生成一个自定义的eventSession ,然后在请求拦截器的header里面加上该字段,这样埋点接口和点击之后执行的接口就可以关联起来了。具体实现如下
1,监听button点击事件
App.vue
<template>
<div id="app">
<router-view />
</div>
</template>
<script>
import { mapGetters } from 'vuex';
import { saveOperateInfo } from '@/api/tool/gen.js';
export default {
name: 'App',
computed: {
...mapGetters(['userId', 'userName', 'device'])
},
//埋点
mounted() {
// 监听click事件
window.addEventListener(
'mousedown',
(e) => {
var targetArea = document.getElementsByTagName('button');
for (let n in targetArea) {
if (HTMLButtonElement === targetArea[n].constructor) {
if (targetArea[n] && targetArea[n].contains(e.target)) {
let eventSession = new Date().getTime() + this.userId.toString();
this.$store.commit('SET_EventSession', eventSession);
let params = {
url: location.pathname,
button: targetArea[n].innerText,
remark: '',
session: eventSession,
platform: this.device === 'mobile' ? 'mobile' : 'web',
userId: this.userId,
userName: this.userName
};
// 下面开始执行请求,传递参数给后端
this.clickOperateInfo(params);
}
}
}
},
true
);
},
methods: {
clickOperateInfo(params) {
saveOperateInfo(params);
}
}
};
</script>
只有箭头指向的那句是我前面讲得,
2,监听进入页面,调一次接口,在你的路由的前置守卫里面写,
router.beforeEach((to, from, next) => {
clickOperateInfo();
})