UNPKG

uniapp-tracing

Version:

uniapp小程序端埋点

104 lines (88 loc) 2.23 kB
// Config import { tracingPvStartKey } from "../config/cache-keys"; // Hooks import { currentRoute } from "../hooks/useRoute"; // Utils import getCurrentTime from "../utils/get-current-time"; import handleQueue from "../utils/handle-queue"; /** * pv埋点 * 记录:页面A-->页面B * 不记录:应用销毁,页面A-->销毁页面A */ const pvMixin = { /** * 下划线写法避免mixin引入冲突 */ data() { return { tracing_pv: { type: "pv", path: "", targetPath: "", startTime: "", endTime: "", }, }; }, onLoad() { // 必须在onLoad时获取全路径 this.tracing_pv.path = currentRoute(); }, onShow() { // 页面打开时获取最新时间 this.tracing_pv.startTime = getCurrentTime(); }, onHide() { this.$leavePage(); }, onUnload() { this.$leavePage(); }, methods: { /** * 离开页面时进行的操作 * 1.进入页面B,完成pv一次周期 * 2.离开页面A,开始pv一次周期 */ $leavePage() { this.$nextTick(() => { // 1. this.$tracingPvEnd(); // 2. this.$tracingPvStart(); }); }, /** * 进入页面B,完成pv一次周期 * 1.补充记录targetPath * 2.提交一个完整的pv周期至埋点队列 */ $tracingPvEnd() { uni.$once(tracingPvStartKey, (tracingPvStart) => { const targetPath = currentRoute(); // 应用销毁,即页面销毁时不记录 if (!targetPath) { return; } const tracingPv = { ...tracingPvStart, targetPath }; handleQueue(tracingPv); }); }, /** * 离开页面A,开始pv一次周期 * 1.获取离开时间 * 2.缓存周期开始的数据 */ $tracingPvStart() { const endTime = getCurrentTime(); const data = { ...this.tracing_pv, endTime }; // 停留时间为0时不记录 if (data.startTime === data.endTime) { return; } uni.$emit(tracingPvStartKey, data); }, }, }; export default pvMixin;