Here, in this article, we will learn how to add google analytics to vue application. We will be using vue-gtag
module to add google analytics id in Vue.
Analytics help us to gather information about how our website is performing by giving us data on traffic, page views, etc.
To add
vue-gtag
in your project you need to have Vue ^2.0.0 or higher.
Add Google Analytics to Vue
To add a google analytics id to your Vue project follow the steps below:
Step 1 : First add vue-gtag
to your application.
npm add vue-gtag
Step 2: Now import it into your main.js
file.
import Vue from "vue";
import App from "./App.vue";
import VueGtag from "vue-gtag";
Vue.use(VueGtag, {
config: { id: "G-123456XXX" }
});
new Vue({
render: h => h(App)
}).$mount("#app");
Add your GA4 Analytics Id( G-123456XXX ) in the id field as shown above.
NOTE: you can use both Universal Analytics Id (UA-1235473-1) and also Google Analytics 4 ( G-123XXXX ) Id in
vue-gtag
config
Enable Auto-Tracking in vue-gtag.
To track all the routes in your Vue SPA application, just pass the VueRouter
Instance in your vue-gtag
config. It will automatically start tracking all the pages.
import Vue from "vue";
import App from "./App.vue";
import VueGtag from "vue-gtag";
import router from './router' // path to the router.js file
Vue.use(VueGtag, {
config: { id: "UA-1234567-1" }
}, router);
new Vue({
router,
render: h => h(App)
}).$mount("#app");
That’s it, now google analytics is successfully added to your vue.
Learn how to add Analytics in the Nuxt application, Add Google Analytics in Nuxt.