miguel.nz

How to use Google Analytics with vue-cli and webpack.

July 6, 2016   |   1 minute read.

This post is from 2016 and probably the info below is out of date.

This article will help you how to add Google analytics by using Analytics.js into your vue-cli webpack project. This is one way to do it, if you have a better way please let me know 🙂

I assume that you’re also using vue-router

1. Insert the Google analytics script inside your index.html

You might have a better way to add external javascript into your project. At the moment I’ll just show you to connect Google Analytics with Vue.

1. Create your google_analytics.js snippet:

module.exports = {
	init(){
		window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
		ga('create', 'UA-80XXXXXX-1', 'auto');
		ga('send', 'pageview');
	}
}

3. Add your file to your main.js

var google_analytics = require('./js/google_analytics.js')

4. Initialize your Google Analytics tracker on your router.start (main.js)

router.start(App,'body', function(){
	google_analytics.init()
})

5. Send your page info via router.beforeEach hook (main.js)

router.beforeEach(function (transition) {
	ga('send', {
	  hitType: 'pageview',
	  page: transition.to.path,
	  location: window.location.origin + transition.to.path,
	  title: transition.to.name
	});
})

Ta dah!. That’s all 🙂

Notes

  • – This is just one way to go, you might want to use the function ga(‘send’, … ) and customise these arguments inside each .vue file so you can send different data.
  • transition.to.name might not be the Title of your page but the name of your template.