本文小编为大家详细介绍“vue怎么自定义指令进行前端埋点”,内容详细,步骤清晰,细节处理妥当,希望这篇“vue怎么自定义指令进行前端埋点”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

创新互联建站专业为企业提供茶陵网站建设、茶陵做网站、茶陵网站设计、茶陵网站制作等企业网站建设、网页设计与制作、茶陵企业网站模板建站服务,十年茶陵做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。
代码实现
Click 类封装
点击事件的处理相对比较简单,每次点击触发数据上报即可:
// src/directives/track/click.js
import { sendUBT } from "../../utils/ctrip"
export default class Click {
add(entry) {
// console.log("entry", entry);
const traceVal = entry.el.attributes["track-params"].value
const traceKey = entry.el.attributes["trace-key"].value
const { clickAction, detail } = JSON.parse(traceVal)
const data = {
action: clickAction,
detail,
}
entry.el.addEventListener("click", function() {
console.log("上报点击埋点", JSON.parse(traceVal))
console.log("埋点key", traceKey)
sendUBT(traceKey, data)
})
}
}Exposure 类封装
曝光的相对复杂一些。
首先通过new IntersectionObserver() 实例化一个全局_observer,如果得到有效曝光的(这里当元素出现一半以上则进行曝光),就去获取 DOM 节点上的trace-key(埋点 key)和track-params(埋点 value)。
// src/directives/track/exposure.js
import "intersection-observer"
import { sendUBT } from "../../utils/ctrip"
// 节流时间调整,默认100ms
IntersectionObserver.prototype["THROTTLE_TIMEOUT"] = 300
export default class Exposure {
constructor() {
this._observer = null
this.init()
}
init() {
const self = this
// 实例化监听
this._observer = new IntersectionObserver(
function(entries, observer) {
entries.forEach((entry) => {
// 出现在视窗内
if (entry.isIntersecting) {
// 获取参数
// console.log("埋点节点", entry.target.attributes);
const traceKey = entry.target.attributes["trace-key"].value
const traceVal = entry.target.attributes["track-params"].value
console.log("traceKey", traceKey)
console.log("traceVal", traceVal)
const { exposureAction, detail } = JSON.parse(traceVal)
const data = {
action: exposureAction,
detail,
}
// 曝光之后取消观察
self._observer.unobserve(entry.target)
self.track(traceKey, data)
}
})
},
{
root: null,
rootMargin: "0px",
threshold: 0.5, // 元素出现面积,0 - 1,这里当元素出现一半以上则进行曝光
}
)
}
/**
* 元素添加监听
*
* @param {*} entry
* @memberof Exposure
*/
add(entry) {
this._observer && this._observer.observe(entry.el)
}
/**
* 埋点上报
*
* @memberof Exposure
*/
track(traceKey, traceVal) {
// console.log("曝光埋点", traceKey, JSON.parse(traceVal));
sendUBT(traceKey, traceVal)
}
}指令封装
有了点击和曝光类,下一步就是 Vue 指令的封装了,也是之所以能实现半自动埋点的核心。
这里存在一个场景就是对于同一个按钮或者图片,同时存在既需要点击埋点又需要曝光埋点的场景。所以在指令的设计时支持了单独传入和同时传入的场景:
v-track:click|exposurev-track:exposure
// src/directives/track/index.js
import Vue from "vue"
import Click from "./click"
import Exposure from "./exposure"
// 实例化曝光和点击
const exp = new Exposure()
const cli = new Click()
Vue.directive("track", {
bind(el, binding) {
// 获取指令参数
const { arg } = binding
arg.split("|").forEach((item) => {
// 点击
if (item === "click") {
cli.add({ el })
} else if (item === "exposure") {
exp.add({ el })
}
})
},
})同时需要在src/index.js引入即可:
import "./directives/track"
使用
在需要埋点的地方使用也是很简单的:
读到这里,这篇“vue怎么自定义指令进行前端埋点”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注创新互联行业资讯频道。
当前标题:vue怎么自定义指令进行前端埋点
标题链接:http://www.jxjierui.cn/article/ipsioj.html


咨询
建站咨询
