Previously the module is called
@nuxtjs/google-tag-manager
.
With @nuxtjs/gtm
, you can easily make collaboration of Google Tag Manager, or GTM and Goole Analytics, or GA.
This introduces you to how to use it with TypeScript.
(At the point of this post is published, TypeScript is not supported by the module.)
Here is the overview of how it works.
As noticed from the image above, there are 3 main parts to setup: Nuxt.js, GTM, and GA.
Nuxt.js
Install @nuxtjs/gtm
yarn add @nuxtjs/gtm
or
npm i -S @nuxtjs/gtm
nuxt.config.ts
Add a configuration to plugins and modules part.
This time, let me create a plugin plugins/gtm.ts
.
plugins: [
{ src: '~plugins/gtm', ssr: false },
],
modules: [
'@nuxtjs/gtm',
],
plugins/gtm.ts
// This is required because @nuxtjs/gtm does not support TypeScript
declare module 'vue/types/vue' {
interface Vue {
$gtm: any
$gtmConfig: any
$gtmPush: (category: string, key: string, params?: any) => void
}
}
export default ({ app }, inject) => {
/**
This specifies a list of gtm parameters.
It can be defined in a separate ts file which can be imported here.
**/
const gtmConfig = {
event: 'nuxtEvent', // This is set as a trigger event name on GTM
items: {
TopPageNavigation: {
menu1: {
eventCategory: 'TopPage navigation',
eventAction: 'menu 1 click',
eventLabel: 'sample label',
eventValue: 'sample value',
},
menu2: {
eventCategory: 'TopPage navigation',
eventAction: 'menu 2 click',
eventLabel: 'sample label',
eventValue: 'sample value',
},
...
},
}
/**
This is called in templates
**/
const gtmPush = (
category: string,
key: string,
props?: {
eventCategory: string
eventAction: string
eventLabel: string
eventValue: string
}
) => {
const {
eventCategory,
eventAction,
eventLabel,
eventValue,
} = gtmConfig.items[category][key]
// Call @nuxtjs/gtm module
app.$gtm.push({
event: gtmConfig.event,
eventCategory: props?.eventCategory ?? eventCategory,
eventAction: props?.eventAction ?? eventAction,
eventLabel: props?.eventLabel ?? eventLabel,
eventValue: props?.eventValue ?? eventValue,
})
}
// Make `gtmConfig` and `gtmPush` globally refferenced
inject('gtmConfig', gtmConfig)
inject('gtmPush', gtmPush)
}
Call gtmPush() from templates
<template>
<section>
<nav>
<ol>
<li v-for="menu in menus" :key="menu.id">
<a href="#" @click.prevent="onClickMenu(menu)">{{ menu.name }}</a>
</li>
</ol>
</nav>
</section>
</template>
<script lang="ts">
type Menu = {
name: string
slug: string
}
...
private menus: Menu[] = [
{ name: 'Menu 1', slug:'menu1' },
{ name: 'Menu 2', slug:'menu2' },
]
private onClickMenu(menu: Menu) {
this.$router.push(`/${menu.slug}`)
this.$gtmPush('topPageNavigation', menu.slug)
}
...
</script>
GTM
On GTM console, you need to setup 1. variables, 2. triggers, and 3. tags.
Variables
Triggers
Tags
GA
After finishing the configuration on Nuxt and GTM, please check the event is tracked properly on GA realtime event tracking page.