问题:如何在 VueJS 单页应用中添加 Matomo 跟踪代码?

我想确认我是否在 VueJS 框架内的单页应用程序中正确设置了分析跟踪设置。

我正在使用 Matomo 的 Vue 插件,可以在此处找到:https://github.com/AmazingDreams/vue-matomo

我在我的main.js入口文件中导入了 VueMatomo 插件,如下所示:

import VueMatomo from 'vue-matomo';

然后,我将 VueMatomo 分配为我的main.js文件中的全局方法,如下所示:

Vue.use(VueMatomo, {
   // Configure your matomo server and site
      host: 'https://matomo.example.com', <-- i configured this to match my real site
      siteId: 5, <--- i configured this to match my real site

  // Enables automatically registering pageviews on the router
      router: router,

  // Enables link tracking on regular links. Note that this won't
  // work for routing links (ie. internal Vue router links)
  // Default: true
      enableLinkTracking: true,

  // Require consent before sending tracking information to matomo
  // Default: false
      requireConsent: false,

  // Whether to track the initial page view
  // Default: true
      trackInitialView: true,

  // Changes the default .js and .php endpoint's filename
  // Default: 'piwik'
      trackerFileName: 'piwik',

  // Whether or not to log debug information
  // Default: false
      debug: false
});

这使我可以访问组件中的 Matomo API (_paq)。但是,这就是我感到困惑的地方。

例如,我有一个名为overview.vue的视图,它是该站点的主页。在这个 vue 模板中,我的created()挂钩中有以下代码。由于我使用的是 SPA,我需要以某种方式获取用户所在页面的名称并将其推送到 Matomo 报告工具。这就是我所做的:

<template>...snip...</template>

<script>
export default {
  name: 'OverView',
  created: function() {
        window._paq.push(['setCustomUrl', '/' + window.location.hash.substr(1)]);
        window._paq.push(['setDocumentTitle', 'Overview Page']);
        window._paq.push(['trackPageView']);
  }
};
</script>

以上内容是否足够,或者是否有更好的生命周期挂钩(已安装?)用于跟踪代码?也许导航守卫更合适?

谢谢

解答

我让 matomo 在我的 vue.js 应用程序(v 2.6.10)上工作。

我正在使用来自https://matomo.org/的试用帐户

在我的main.js文件中:

// Analytics
import VueMatomo from "vue-matomo";

Vue.use(VueMatomo, {
  host: "https://example.matomo.cloud", // switch this to your account
  siteId: 1,                            // switch this as well you can find the site id after adding the website to the dashboard. 

  router: router,

  enableLinkTracking: true,

  requireConsent: false,

  trackInitialView: true,

  trackerFileName: "piwik",

  debug: true
});

我可以确认我所有的嵌套路由都被跟踪了。我可以看到我在 matomo 仪表板上查看了哪些页面。

要使自定义事件正常工作,只需添加以下内容:this.$matomo.trackEvent("Event Category", "Event Name", "event action");

为了给出一些上下文,对于我的应用程序,我在计算属性中使用它:

  computed: {
    selectedMapDataType: {
      get() {
        return this.$store.state.mapDataType;
      },
      set(selected) {
        this.$matomo.trackEvent("Dashboard Update", "Dashboard Data", selected);
        this.$store.dispatch("updateMapDataType", selected);
      }
    },
...}
Logo

前往低代码交流专区

更多推荐