How to install Google Analytics tracking code in Vue.js

in Code Write a comment

In this tutorial, you’ll learn how to easily add a GA tracking code to your Vue.js app.

If you just add GA code to your index.html file it won’t track route changes. Multiple user page views will be counted as one, thus the stats will be wrong.

Luckily, there are available npm-packages out there that allow you to easily add Google Analytics to your app.

One of them is vue-analytics. It is a wrapper of the Google Analytics API. You can add it to your app with the following command:

npm i -S vue-analytics

It will install an npm package and add it as a dependency to the package.json file. Learn more on how to install/uninstall npm packages.

Once installed, you need to add it your Vue application:

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

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

That’s it. It will now track route changes, you can also create custom events, track Vuex calls etc.

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vue-js-google-analytics

PS: Make sure you check other Vue.js tutorials, e.g. how to concatenate variable and text in Vue.js and how to dynamically change the path of href in Vue.js.

Write a Comment

Comment