Vue JS and Vue Router work great together to create fast websites with near instant page loads, but they can throw a bit of a spanner in the works when it comes to registering event in Google Analytics.
That’s because by default Google Analytics sends data to Google every time a new pages is loaded. However, when using Vue Router you technically never leave the landing page – JavaScript magic just makes it seem like you’re browsing between pages.
To bridge the gap there’s a Vue library called vue-gtag
.
Start off by install the library
npm install --save vue-gtag
Import it into your main app JS file, including your Google Analytics ID (to replace UA-1234567-1 below)
import VueRouter from 'vue-router';
import VueGtag from "vue-gtag";
The basic set up for vue-gtag
looks like this
Vue.use(VueGtag, {
config: { id: "UA-1234567-1" }
});
Since we’re using Vue Router, we can automatically add our router to the vue-gtag
declaration. Make sure that the code to use vue-gtag
is placed after the code for the router, so we can reference the variable that contains the router
Vue.use(VueGtag, {
config: { id: "UA-1234567-1" }
}, router);
Once you’re done your main app JS file should look something like this
window.Vue = require('vue');
import VueRouter from 'vue-router';
import VueGtag from "vue-gtag";
<code>
Vue.use(VueRouter);
<code>
/**
* Components
*/
import Homepage from ‘./components/Homepage.vue’;
import Thankyou from ‘./components/Thankyou.vue’;
<code>
/**
* Vue Router
*/
<code>
const router = new VueRouter({
mode: ‘history’,
routes: [
{
path: ‘/’,
component: Homepage,
name: ‘Homepage’,
props: true
},
{
path: ‘/thank-you’,
component: Thankyou,
name: ‘Thankyou’,
props: true
},
],
});
<code>
/**
* Vue Gtag
*/
Vue.use(VueGtag, {
config: { id: “GTM-53F87G5” }
}, router);
/**
* Our application
*/
const app = new Vue({
el: '#app',
router: router,
});