vue自定义指令实现数据埋点

本文介绍了如何在Vue应用中使用自定义指令`tracking`,结合debounce防抖技术,实现点击事件后的后台数据追踪,同时通过`$tracking`方法简化调用。展示了如何安装指令并正确使用在HTML元素上。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.埋点指令

import { debounce, eventTrack } from "../utils/common"

const install = function (Vue) {

  const INTERVAL = 300;
  Vue.directive('tracking', {
    bind(el, binding) {
      el.addEventListener('click', debounce(function () {
          //调用后台接口保存数据
        eventTrack(binding.value)
      }, INTERVAL)
        , false)
    }
  })

  Vue.prototype.$tracking = function (dictCode) {
    debounce(function (dictCode) {
        eventTrack(dictCode)
    }, INTERVAL)(dictCode)
  }

}
if (window.Vue) {
  Vue.use(install); // eslint-disable-line
}

export default install

2. main.js注册指令

import directive from './directive' // directive

Vue.use(directive)

3.使用方式如下

   <div class="index-tab-item" v-tracking="'shouye:shipingtai'"  @click="handleChange('shi')">
        切换
      </div>

4.扩展debounce防抖和eventTrack请求后台

/**
 * 函数防抖
 */
let  timer = null;
export function debounce(fn, interval = 300) {
  return function () {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, arguments);
    }, interval);
  };
}
//請求接口
export function eventTrack(code) {
  let users = JSON.parse(localStorage.getItem('userinfos'));
  let userInfo = {
    "userId": users.id,
    "userName": users.userName,
    "userRealName": users.realname,
  }
  if (code) {
    eventTracking({
      eventCode: code,
      ...userInfo
    })
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值