How to add Google Analytics in Vue?
Short tutorial on how to integrate google analytics in our vue application. we will be using vue-gtag npm module to add analytics Id in our website and application.
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-gtagin 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-gtagconfig
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.
Related Posts
Easy Way to use localStorage with Vue
Short article on how to use local storage with Vue and learn saving and storing data in local storage with the setItem() and getItem() methods.
Force update Vue to Reload/Rerender component
Short tutorial on how to correctly force update Vue.js component to reload or rerender. The component is reinitialized without having to do a browser refresh.
Set and get cookies in a browser in Vue App
Find out how to set and get cookies in a browser for your webpage in Vue using vue-cookies package.
Save vuex state after page refresh in Vue App
Short tutorial on how to save (or persist) data in a vue application using Vuex and vuex-persist npm package.
