Vue 自定義指令上報 Google Analytics 事件統計

發現問題

通常前端開發離不開數據統計,咱們常常須要接入統計服務以方便運營,例如如今須要統計一個按鈕javascript

<template>
  <button @click="handleClick" />
</template>

<script>
export default {
  methods: {
    handleClick() {
      window.alert('button click')
    }
  }
}
</script>

引入 ga 後是這樣上報的html

handleClick() {
  window.alert('button click')

  const params = {
    hitType: 'event',
    eventCategory: 'button',
    eventAction: 'click',
    eventLabel: 'click label'
  }

  window.ga('send', params)
}

很簡單!前端

但當頁面的按鈕增長,咱們幾乎要在全部 handle 事件裏侵入統計代碼,和業務邏輯混在一塊兒vue

不夠優雅!java

怎麼優雅

咱們嘗試利用 Vue 的指令來自定義統計,這是我最終想要的統計方式code

只須要在 template 裏聲明好統計參數,用戶點擊則觸發上報htm

<template>
  <button @click="handleClick"
          v-ga="{
            eventCategory: 'button',
            eventLabel: 'button click'
          }" />
</template>

抽離統計

將上報統計代碼單獨個方法出來事件

./services/analyst.jsip

export function send(data = {}) {
  const params = {
    hitType: 'event',
    eventCategory: 'button',
    eventAction: 'click',
    eventLabel: 'click label'
  }

  window.ga('send', Object.assign({}, params, data))
}

編寫指令

監聽帶有 v-ga 指令的元素,統一處理上報開發

./plugins/analyst.js

import * as analyst from './services/analyst'

const plugin = Vue => {
  Vue.directive('ga', {
    bind(el, binding) {
      el.addEventListener('click', () => {
        // binding.value 拿到 v-ga 指令的參數
        analyst.send(binding.value)
      })
    },

    unbind(el) {
      el.removeEventListener('click', () => {})
    }
  })
}

export default plugin

最終調用

import Vue from 'vue'
import GaPlugin from './plugins/analyst'

Vue.use(GaPlugin)
相關文章
相關標籤/搜索