基于vuex下的前端埋点,即用户行为上报

288 阅读2分钟

前言

公司阅读平台项目增加了统计用户行为分析的这一需求,便着手设计方案,第一时间想到以vuex记录用户行为,这样全局皆可快捷记录行为,统一上报,代码也方便维护。

正文

项目采用vue-cli + vue-router3.0构建,在main.js中引入vuex,store/index.js如下

// store/index.js
state: {
    actions: [] // { PageCode: '', ToPageCode: '', ActionType: 'CLICK', ActionValue: '', TimeStamp: parseInt(new Date().getTime() / 1000), param: {} }
},
mutations: {
    ADD_ACTIONS(state, action) {
      state.actions.push(action)
    },
    CLEAR_ACTIONS(state) {
      state.actions = []
    }
},
actions: {
    // 广泛的行为记录
    RecordAction({ commit, state }, param) {
      const actionModule = {
        PageCode: '',
        ToPageCode: '',
        ActionType: 'CLICK',
        ActionValue: '',
        TimeStamp: parseInt(new Date().getTime() / 1000),
        param: {}
      }
      const action = { ...actionModule, ...param }
      commit('ADD_ACTIONS', action)
    },
    // 清空行为数组
    ClearActions({ commit }) {
      commit('CLEAR_ACTIONS')
    }
},

各页面通过dispatch上报用户行为

this.$store.dispatch('RecordAction', {PageCode: 'BOOK_STORE_PAGE', ToPageCode: 'READ_PAGE', ActionValue: 'CLICK_BOOK', param: { bookId: '415648915' }})

到此用户的行为已经完成在前端的记录,接下来是采用怎样的方案提交至后端 用户的每一次行为记录后立马上报至后端的话请求次数太多,尤其是在一些点的频繁操作,所以当行为数组积累满5条时自动上报用户行为,但是这样可能因为用户突然关闭页面(项目应用于微信浏览器)导致一些记录丢失,为此增加补充,每隔三秒检查一次行为数组,有则上报用户行为并清空行为数组,没有则不做处理,这样大大减少用户行为的丢失。 store/index.js中的actions修改如下

// 广泛的行为记录
    RecordAction({ commit, state }, param) {
      const actionModule = {
        PageCode: '',
        ToPageCode: '',
        ActionType: 'CLICK',
        ActionValue: '',
        TimeStamp: parseInt(new Date().getTime() / 1000),
        param: {}
      }
      const action = { ...actionModule, ...param }
      commit('ADD_ACTIONS', action)
      // 检测行为数组长度,大于等于5时上报行为
      if (state.actions.length >= 5) {
        const report = {
          publicId: state.userInfo.publicId,
          list: state.actions
        }
        // 提交行为数组
        statistics(report)
        commit('CLEAR_ACTIONS')
      }
    },

在App.vue中增加如下代码

import { mapActions } from 'vuex'
created() {
    setInterval(this.reportAction, 3000)
},
methods: {
    ...mapActions({
      reportAction: 'AutoReportActions'
    })
}

这是一种不算完美的方案,欢迎各位大牛看到有更好的方案分享。