useTracking.js 2.24 KB
/**
 * 埋点系统封装
 * @module useTracking
 * @description 提供统一的事件埋点上报功能,支持页面浏览、点击事件和自定义事件。
 */

/**
 * 模拟埋点接口请求
 * @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 = {}) => {
        // 获取当前页面路径
        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
    }
}