前端如何配合后端埋点

发布时间 2023-05-24 18:04:25作者: sinceForever

需求:点击按钮时和进入离开页面时,监听用户行为

  • 本篇文章未写完,过两天需求写完了再更新完整的

思路: 监听点击事件,生成一个自定义的clickSession,然后在请求拦截器的header里面加上该字段,这样埋点接口和点击之后执行的接口就可以关联起来了。具体实现如下

App.vue

<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
import { mapGetters } from 'vuex';

export default {
  name: 'App',
  computed: {
    ...mapGetters(['userId'])
  },
  //埋点
  mounted() {
    //监听click事件
    window.addEventListener(
      'click',
      (res) => {
        let clickSession = this.userId + new Date().getTime();
        this.$store.commit('SET_CLICKSESSION', clickSession);
          //这里的clickSession,很重要,
        console.log(
          'store1---clickSession',
          this.$store.state.user.clickSession
        );

        //下面开始执行请求,传递参数给后端
          this.saveOperateInfo()

      },
      true
    );
  }
};
</script>

只有箭头指向的那句是我前面讲得,

后面会将页面进入离开等都写上,先等我!