useTracking.js
2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
* @Date: 2025-12-24 13:50:03
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2025-12-24 14:19:52
* @FilePath: /mlaj/src/composables/useTracking.js
* @Description: 埋点 Composable, 模拟埋点接口请求
*/
/**
* 模拟埋点接口请求
* @param {Object} data 埋点数据
* @returns {Promise}
*/
const mockTrackRequest = (data) => {
return new Promise((resolve) => {
// 模拟网络延迟
setTimeout(() => {
resolve({ code: 200, message: 'success' })
}, 300)
})
}
/**
* 埋点 Composable
* @returns {Object} 包含埋点方法的对象
*/
export function useTracking() {
/**
* 上报埋点事件
* @param {string} eventType - 事件类型 (如 'page_view', 'click', 'custom', 'error')
* @param {string} actionName - 动作名称 (如 'login_btn_click', 'banner_view')
* @param {Object} [extraData={}] - 额外参数 (业务相关的数据)
*/
const trackEvent = async (eventType, actionName, extraData = {}) => {
// 获取当前页面路径 (简单获取,如果在组件setup中使用window.location)
const pagePath = window.location.pathname + window.location.hash
const payload = {
event_type: eventType,
action_name: actionName,
page_path: pagePath,
timestamp: Date.now(),
extra_data: extraData,
// 这里可以扩展更多公共参数,如:
// device_id: '...',
// user_id: '...',
// platform: 'h5'
}
try {
await mockTrackRequest(payload)
} catch (error) {
console.error('埋点上报失败:', error)
}
}
/**
* 快捷方法:页面浏览埋点
* @param {string} [pageName] - 页面名称
* @param {Object} [extraData] - 额外参数
*/
const trackPageView = (pageName, extraData = {}) => {
trackEvent('page_view', 'view', {
page_name: pageName,
...extraData
})
}
/**
* 快捷方法:点击事件埋点
* @param {string} elementName - 元素名称/动作名称
* @param {Object} [extraData] - 额外参数
*/
const trackClick = (elementName, extraData = {}) => {
trackEvent('click', elementName, extraData)
}
return {
trackEvent,
trackPageView,
trackClick
}
}