Using GA4 in Vue
Setting up GA4 in Vue (version 3) can be done using the vue-gtag plugin (By Matteo Gabriele). This plugin requires Vue ^3.0.0 and needs to be installed using npm:
npm install vue-gtag
I like to have the documentation early in walkthroughs so I can determine if its going to be something I want to actually integrate with. Here is the documentation for this plugin.
Add the plugin to your application:
import { createApp } from "vue";
import App from "./App.vue";
import VueGtag from "vue-gtag";
createApp(App).use(VueGtag, {
config: { id: "GA_MEASUREMENT_ID" }
}).mount("#app");
This is just an example by using the Google Analytics domain ID as a configuration ID, but it is possible to use things like Google Adwords as well, so make sure to read the gtag documentation if you need more insights about what type of tracking code you need to use.
After this, you will be able to use the gtag the library inside your components contextually by accessing it like this example:
export default {
name: 'MyComponent',
methods: {
login () {
this.$gtag.event('login', { method: 'Google' })
}
}
}