• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

    基于Vue+Node.js实现埋点功能全流程

    发布者: 涵韵 | 发布时间: 2025-6-14 15:32| 查看数: 44| 评论数: 0|帖子模式


    要实现用户访问量统计和模块点击统计功能,可以采用以下方案:

    一、前端(Vue)实现


    1. 安装必要的依赖
    1. npm install axios --save  # 用于发送请求
    2. npm install js-cookie --save  # 用于识别用户
    复制代码
    2. 创建埋点工具类 (tracker.js)
    1. import axios from 'axios';
    2. import Cookies from 'js-cookie';

    3. const Tracker = {
    4.   // 初始化用户ID(如果不存在)
    5.   initUserId() {
    6.     let userId = Cookies.get('user_id');
    7.     if (!userId) {
    8.       userId = 'user_' + Math.random().toString(36).substr(2, 9);
    9.       Cookies.set('user_id', userId, { expires: 365 });
    10.     }
    11.     return userId;
    12.   },

    13.   // 发送页面访问埋点
    14.   trackPageView() {
    15.     const userId = this.initUserId();
    16.     const data = {
    17.       userId: userId,
    18.       eventType: 'pageview',
    19.       pageUrl: window.location.href,
    20.       timestamp: new Date().toISOString()
    21.     };
    22.     this.sendData(data);
    23.   },

    24.   // 发送模块点击埋点
    25.   trackModuleClick(moduleName) {
    26.     const userId = this.initUserId();
    27.     const data = {
    28.       userId: userId,
    29.       eventType: 'module_click',
    30.       moduleName: moduleName,
    31.       timestamp: new Date().toISOString()
    32.     };
    33.     this.sendData(data);
    34.   },

    35.   // 发送数据到后端
    36.   sendData(data) {
    37.     axios.post('/api/track', data)
    38.       .catch(error => {
    39.         console.error('Tracking error:', error);
    40.       });
    41.   }
    42. };

    43. export default Tracker;
    复制代码
    3. 在Vue应用中使用


    全局埋点 (main.js)
    1. import Tracker from './utils/tracker';
    2. import router from './router';

    3. // 页面访问埋点
    4. router.afterEach((to, from) => {
    5.   Tracker.trackPageView();
    6. });

    7. // 挂载到Vue原型,方便组件内使用
    8. Vue.prototype.$tracker = Tracker;
    复制代码
    组件内模块点击埋点
    1. <template>
    2.   <div>
    3.     <button @click="handleClick('module1')">模块1</button>
    4.     <button @click="handleClick('module2')">模块2</button>
    5.   </div>
    6. </template>

    7. <script>
    8. export default {
    9.   methods: {
    10.     handleClick(moduleName) {
    11.       // 业务逻辑...
    12.       
    13.       // 埋点
    14.       this.$tracker.trackModuleClick(moduleName);
    15.     }
    16.   }
    17. }
    18. </script>
    复制代码
    二、后端(Node.js)实现


    1. 创建数据库表

    假设使用MySQL:
    1. CREATE TABLE tracking_events (
    2.   id INT AUTO_INCREMENT PRIMARY KEY,
    3.   user_id VARCHAR(255),
    4.   event_type VARCHAR(50),
    5.   page_url VARCHAR(500),
    6.   module_name VARCHAR(100),
    7.   created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    8. );

    9. CREATE TABLE daily_stats (
    10.   id INT AUTO_INCREMENT PRIMARY KEY,
    11.   date DATE UNIQUE,
    12.   total_visits INT DEFAULT 0,
    13.   unique_visitors INT DEFAULT 0,
    14.   created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    15.   updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    16. );

    17. CREATE TABLE module_stats (
    18.   id INT AUTO_INCREMENT PRIMARY KEY,
    19.   module_name VARCHAR(100) UNIQUE,
    20.   click_count INT DEFAULT 0,
    21.   created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    22.   updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    23. );
    复制代码
    2. Node.js 后端接口 (Express示例)
    1. const express = require('express');
    2. const bodyParser = require('body-parser');
    3. const mysql = require('mysql2/promise');
    4. const app = express();

    5. // 数据库连接配置
    6. const pool = mysql.createPool({
    7.   host: 'localhost',
    8.   user: 'root',
    9.   password: 'password',
    10.   database: 'tracking_db',
    11.   waitForConnections: true,
    12.   connectionLimit: 10,
    13.   queueLimit: 0
    14. });

    15. app.use(bodyParser.json());

    16. // 埋点数据接收接口
    17. app.post('/api/track', async (req, res) => {
    18.   try {
    19.     const { userId, eventType, pageUrl, moduleName } = req.body;
    20.    
    21.     // 1. 记录原始事件
    22.     await pool.query(
    23.       'INSERT INTO tracking_events (user_id, event_type, page_url, module_name) VALUES (?, ?, ?, ?)',
    24.       [userId, eventType, pageUrl, moduleName]
    25.     );
    26.    
    27.     // 2. 如果是页面访问,更新每日统计
    28.     if (eventType === 'pageview') {
    29.       await updateDailyStats(userId);
    30.     }
    31.    
    32.     // 3. 如果是模块点击,更新模块统计
    33.     if (eventType === 'module_click' && moduleName) {
    34.       await updateModuleStats(moduleName);
    35.     }
    36.    
    37.     res.status(200).send('OK');
    38.   } catch (error) {
    39.     console.error('Tracking error:', error);
    40.     res.status(500).send('Internal Server Error');
    41.   }
    42. });

    43. // 更新每日统计
    44. async function updateDailyStats(userId) {
    45.   const today = new Date().toISOString().split('T')[0];
    46.   
    47.   // 检查今天是否已有记录
    48.   const [rows] = await pool.query('SELECT * FROM daily_stats WHERE date = ?', [today]);
    49.   
    50.   if (rows.length === 0) {
    51.     // 新的一天,创建新记录
    52.     await pool.query(
    53.       'INSERT INTO daily_stats (date, total_visits, unique_visitors) VALUES (?, 1, 1)',
    54.       [today]
    55.     );
    56.   } else {
    57.     // 更新现有记录
    58.     // 检查用户今天是否已经访问过
    59.     const [visits] = await pool.query(
    60.       'SELECT COUNT(DISTINCT user_id) as user_visited FROM tracking_events ' +
    61.       'WHERE event_type = "pageview" AND DATE(created_at) = ? AND user_id = ?',
    62.       [today, userId]
    63.     );
    64.    
    65.     const isNewVisitor = visits[0].user_visited === 0;
    66.    
    67.     await pool.query(
    68.       'UPDATE daily_stats SET total_visits = total_visits + 1, ' +
    69.       'unique_visitors = unique_visitors + ? WHERE date = ?',
    70.       [isNewVisitor ? 1 : 0, today]
    71.     );
    72.   }
    73. }

    74. // 更新模块统计
    75. async function updateModuleStats(moduleName) {
    76.   await pool.query(
    77.     'INSERT INTO module_stats (module_name, click_count) VALUES (?, 1) ' +
    78.     'ON DUPLICATE KEY UPDATE click_count = click_count + 1',
    79.     [moduleName]
    80.   );
    81. }

    82. // 获取统计数据的接口
    83. app.get('/api/stats', async (req, res) => {
    84.   try {
    85.     // 总访问量
    86.     const [totalVisits] = await pool.query('SELECT SUM(total_visits) as total FROM daily_stats');
    87.    
    88.     // 今日访问量
    89.     const today = new Date().toISOString().split('T')[0];
    90.     const [todayStats] = await pool.query('SELECT * FROM daily_stats WHERE date = ?', [today]);
    91.    
    92.     // 热门模块
    93.     const [popularModules] = await pool.query(
    94.       'SELECT module_name, click_count FROM module_stats ORDER BY click_count DESC LIMIT 5'
    95.     );
    96.    
    97.     res.json({
    98.       totalVisits: totalVisits[0].total || 0,
    99.       todayVisits: todayStats[0] ? todayStats[0].total_visits : 0,
    100.       todayUniqueVisitors: todayStats[0] ? todayStats[0].unique_visitors : 0,
    101.       popularModules: popularModules
    102.     });
    103.   } catch (error) {
    104.     console.error('Error fetching stats:', error);
    105.     res.status(500).send('Internal Server Error');
    106.   }
    107. });

    108. const PORT = 3000;
    109. app.listen(PORT, () => {
    110.   console.log(`Server running on port ${PORT}`);
    111. });
    复制代码
    三、数据可视化

    可以创建一个管理后台页面来展示这些统计数据:
    1. <template>
    2.   <div class="stats-dashboard">
    3.     <h1>网站访问统计</h1>
    4.    
    5.     <div class="stats-grid">
    6.       <div class="stat-card">
    7.         <h3>总访问量</h3>
    8.         <p class="stat-value">{{ stats.totalVisits }}</p>
    9.       </div>
    10.       
    11.       <div class="stat-card">
    12.         <h3>今日访问量</h3>
    13.         <p class="stat-value">{{ stats.todayVisits }}</p>
    14.       </div>
    15.       
    16.       <div class="stat-card">
    17.         <h3>今日独立访客</h3>
    18.         <p class="stat-value">{{ stats.todayUniqueVisitors }}</p>
    19.       </div>
    20.     </div>
    21.    
    22.     <div class="popular-modules">
    23.       <h2>热门模块</h2>
    24.       <ul>
    25.         <li v-for="(module, index) in stats.popularModules" :key="index">
    26.           {{ module.module_name }}: {{ module.click_count }} 次点击
    27.         </li>
    28.       </ul>
    29.     </div>
    30.   </div>
    31. </template>

    32. <script>
    33. import axios from 'axios';

    34. export default {
    35.   data() {
    36.     return {
    37.       stats: {
    38.         totalVisits: 0,
    39.         todayVisits: 0,
    40.         todayUniqueVisitors: 0,
    41.         popularModules: []
    42.       }
    43.     };
    44.   },
    45.   mounted() {
    46.     this.fetchStats();
    47.   },
    48.   methods: {
    49.     async fetchStats() {
    50.       try {
    51.         const response = await axios.get('/api/stats');
    52.         this.stats = response.data;
    53.       } catch (error) {
    54.         console.error('Error fetching stats:', error);
    55.       }
    56.     }
    57.   }
    58. };
    59. </script>

    60. <style>
    61. .stats-dashboard {
    62.   max-width: 1200px;
    63.   margin: 0 auto;
    64.   padding: 20px;
    65. }

    66. .stats-grid {
    67.   display: grid;
    68.   grid-template-columns: repeat(3, 1fr);
    69.   gap: 20px;
    70.   margin-bottom: 30px;
    71. }

    72. .stat-card {
    73.   background: #f5f5f5;
    74.   padding: 20px;
    75.   border-radius: 8px;
    76.   text-align: center;
    77. }

    78. .stat-value {
    79.   font-size: 24px;
    80.   font-weight: bold;
    81.   margin: 10px 0 0;
    82. }

    83. .popular-modules ul {
    84.   list-style: none;
    85.   padding: 0;
    86. }

    87. .popular-modules li {
    88.   padding: 10px;
    89.   background: #f0f0f0;
    90.   margin-bottom: 5px;
    91.   border-radius: 4px;
    92. }
    93. </style>
    复制代码
    四、优化建议


    • 性能优化

      • 前端可以使用节流(throttle)或防抖(debounce)技术减少高频点击的埋点请求
      • 后端可以考虑使用批量插入代替单条插入

    • 数据准确性

      • 使用更可靠的用户识别方式,如结合IP、设备指纹等
      • 考虑使用Web Beacon API在页面卸载时发送数据

    • 扩展性

      • 可以添加更多事件类型(如停留时长、滚动深度等)
      • 可以按时间段(小时/天/周)分析访问模式

    • 隐私合规

      • 添加用户同意机制(如GDPR合规)
      • 提供隐私政策说明数据收集用途

    这个方案提供了完整的从前端埋点到后端存储再到数据展示的全流程实现,你可以根据实际需求进行调整和扩展。
    以上就是基于Vue+Node.js实现埋点功能全流程的详细内容,更多关于Vue+Node.js埋点功能的资料请关注脚本之家其它相关文章!

    来源:https://www.jb51.net/javascript/340097mog.htm
    免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

    本帖子中包含更多资源

    您需要 登录 才可以下载或查看,没有账号?立即注册

    ×

    最新评论

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表