baidu-tongji.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. export default function (c, i) {
  2. const { app, $auth, store } = c;
  3. window._hmt = window._hmt || [];
  4. window._hmt.push(['_setAutoPageview', false]);
  5. window._hmt.push(['_setCustomVar', 1, 'MODE', process.env.MODE, 1]);
  6. app.router.afterEach((to, from) => {
  7. // 上报PV
  8. window._hmt.push(['_trackPageview', c.base + to.path.slice(1)]);
  9. });
  10. app.head.script = app.head.script || [];
  11. app.head.script.push({
  12. src: `https://hm.baidu.com/hm.js?${process.env.BAIDU_TONGJI_KEY}`,
  13. id: 'baidu-tongji',
  14. });
  15. // $auth.
  16. const setUserId = () => {
  17. window._hmt.push(['_setCustomVar', 2, 'userId', $auth.user?.id ?? 0, 2]);
  18. };
  19. store.watch(
  20. (state, getter) => {
  21. return $auth.user;
  22. },
  23. (user) => setUserId,
  24. {},
  25. );
  26. setUserId();
  27. i('tongji', {
  28. // 上报pv
  29. trackPageview: (path) => window._hmt.push(['_trackPageview', path]),
  30. // 上报事件
  31. trackEvent: (category, action, optLabel, optValue) =>
  32. window._hmt.push(['_trackEvent', category, action, optLabel, optValue]),
  33. });
  34. }