How does the vue-cli project use Google Analytics correctly?

foreword

The most convenient way is to use vue-analytics: https://github.com/MatteoGabriele/vue-analytics .

The package is there, but when you actually use it, you will find that Google Analytics (hereinafter referred to as GA) may not detect it or there may be a problem of missing statistics. The theme of this article is to discuss a few basic checkpoints and explain the basic usage of GA to ensure that GA works properly.

This article is divided into the following sections:

  • How to properly initialize GA
  • GA basic usage: page tracking and event tracking
  • How to check if GA is working
  • Steps to add GA to vue-cli project
  • Recommended Reading

How to properly initialize GA

The following code must be placed in the html file according to the official requirements of Google, and should be placed </head>before:

      <script>
        (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
        ga('create', 'UA-XXX', 'auto'); // 将`UA-XXX`换成自己的ID
        ga('send', 'pageview');
      </script>

There are other ways to get GA code working, but introduce some problems. For example, when we use vue, we naturally wonder if we can complete the initialization directly in vue, and do not want to modify the html. However, there are two problems in the actual measurement.

  • The first is that the background of GA cannot be detected, similar to the following prompt:

  • The second is that Google's other products, such as Ad Words, and GAcooperation, will also require GA code </head>to work before.

To sum up, in the initialization, we can only honestly follow the method of GOOGLE.

GA basic usage: page tracking and event tracking

Event tracking and event tracking are the most basic and most important uses of GA, especially page tracking.

Let’s talk about page tracking first: In general websites, you only need htmlto add a GA code to complete page tracking, but SPAit is not possible for it, because the jump between routes does not refresh the page, and GA cannot perceive it. So it needs to be triggered manually. In vue-clithe project, you can use the following code for simple processing:

router.afterEach((to, from) => {
  ga('set', 'page', to.path)
  ga('send', 'pageview')
})

It is recommended to use vue-analyticsit and follow the official guidance, which can save a lot of trouble. Otherwise, you need to manually handle the abnormal situations such as the first entry of repeated counting and the absence of GA.

import Vue from 'vue'
import VueRouter from 'vue-router'
import VueAnalytics from 'vue-analytics'

const router = new VueRouter({
  router: // your routes
})

Vue.use(VueAnalytics, {
  id: 'UA-XXX-X',
  router,
  autoTracking: {
    pageviewOnLoad: false
  }
})

Link: https://github.com/MatteoGabriele/vue-analytics/blob/master/docs/page-tracking.md

Event Tracking:
The native code is

ga.event('category', 'action', 'label', 123)

If vue-analytics is used, it is:

this.$ga.event('category', 'action', 'label', 123)

Link: https://github.com/MatteoGabriele/vue-analytics/blob/master/docs/event-tracking.md

It is worth mentioning that the four parameters of the event are set:

  • category: generally a large category, such as brand, video, etc.
  • action: generally a specific operation, such as download, play, click, etc.
  • label: usually some additional information, such as the specific brand ID, the title of the video, etc.
  • value: any metric value, must be a positive integer, such as the value of the brand, the duration of the video, etc.

How to check if GA is working properly?

1.下载Chrome插件:Tag Assistant(https://chrome.google.com/webstore/detail/tag-assistant-by-google/kejbdjndbnbjgmefkgdddjlbokphdefk)

2. How to check the initialization: Click Record below, then refresh the page, and then you can see the currently loaded TAG. Google Analytics is just one of them, there are others like Remarketing Tag (remarketing code), etc., as shown in the figure below, here we only care about Google Analytics. If it is green, it means normal, otherwise, check the problem according to the prompts.

3. How to check PageView and Event: Click Goole Analyticsthat option to see the details of GA. If there is a PageView or Event sent, you can see the statistics below.
3.1 Specific information of Pageview: As shown in the figure below, a PageView of the /login page is issued. If there are multiple different PageViews, click left and right to switch one by one. I generally use this panel to confirm whether multiple identical PageViews are issued after the page is loaded, and whether a PageView is issued when the route is switched.

3.2 The specific information of the event: The viewing method of the event is similar to the pageview, that is, the content becomes the category, action, label, value and other information of the event. I mainly use it to confirm that the event is emitted and the parameters are correct.

vue-cliThe detailed steps of adding GAcode to the project

config/prod.env.js, add the GA code ID:

'use strict'

module.exports = {
  NODE_ENV: '"production"',
  GA: `"UA-113937480-1"`
}

build/webpack.prod.conf.jsFound HtmlWebpackPlugin, finally added gaoptions:

    new HtmlWebpackPlugin({
      filename: process.env.NODE_ENV === 'testing'
        ? 'index.html'
        : config.build.index,
      template: 'index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency',
      favicon: './static/bitbug_favicon.ico',
      ga: env.GA // 添加ga选项,以便在index.html中可以引用
    }),

index.html, </head>added before, pay special attention to its GA's ID is read from the configuration rather than hard-coded

      <script>
        (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
        ga('create', <%= htmlWebpackPlugin.options.ga %>, 'auto');
        ga('send', 'pageview');
      </script>

src/main.jsIntroduce vue-analytics, refer to the source code

import App from './App'
import router from './router'
import VueAnalytics from 'vue-analytics'


// GA初始化
if (process.env.GA) {
  Vue.use(VueAnalytics, {
    id: process.env.GA, // 从配置中读取
    disableScriptLoader: true, // 必须在html中完成初始化,这里显式禁止去下载ga脚本
    router, // 确保路由切换时可以自动统计
    autoTracking: {
      pageviewOnLoad: false // 当通过网址进来时已经GA在初始化时就发起一次pageview的统计,这里不要重复统计
    }
  })
}

Recommended reading

About Google Analytics Events

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326273532&siteId=291194637