發(fā)現(xiàn)問(wèn)題
一般前端開(kāi)發(fā)離不開(kāi)數(shù)據(jù)統(tǒng)計(jì),我們經(jīng)常需要接入統(tǒng)計(jì)服務(wù)以方便運(yùn)營(yíng),例如現(xiàn)在需要統(tǒng)計(jì)一個(gè)按鈕
<template> <button @click="handleClick" /></template><script>export default { methods: { handleClick() { window.alert('button click') } }}</script>引入 ga 后是這樣上報(bào)的
handleClick() { window.alert('button click') const params = { hitType: 'event', eventCategory: 'button', eventAction: 'click', eventLabel: 'click label' } window.ga('send', params)}很簡(jiǎn)單!
但當(dāng)頁(yè)面的按鈕增加,我們幾乎要在所有 handle 事件里侵入統(tǒng)計(jì)代碼,和業(yè)務(wù)邏輯混在一起
不夠優(yōu)雅!
怎么優(yōu)雅
我們嘗試?yán)?Vue 的指令來(lái)自定義統(tǒng)計(jì),這是我最終想要的統(tǒng)計(jì)方式
只需要在 template 里聲明好統(tǒng)計(jì)參數(shù),用戶點(diǎn)擊則觸發(fā)上報(bào)
<template> <button @click="handleClick" v-ga="{ eventCategory: 'button', eventLabel: 'button click' }" /></template>抽離統(tǒng)計(jì)
將上報(bào)統(tǒng)計(jì)代碼單獨(dú)個(gè)方法出來(lái)
./services/analyst.js
export function send(data = {}) { const params = { hitType: 'event', eventCategory: 'button', eventAction: 'click', eventLabel: 'click label' } window.ga('send', Object.assign({}, params, data))}編寫(xiě)指令
監(jiān)聽(tīng)?zhēng)в?v-ga 指令的元素,統(tǒng)一處理上報(bào)
./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 指令的參數(shù) analyst.send(binding.value) }) }, unbind(el) { el.removeEventListener('click', () => {}) } })}export default plugin最終調(diào)用
import Vue from 'vue'import GaPlugin from './plugins/analyst'Vue.use(GaPlugin)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注