Google Tag Manager
Google Tag Manager is a tag management system that allows you to quickly and easily update tags and code snippets on your website or mobile app, such as those intended for traffic analysis and marketing optimization.
useScriptGoogleAnalytics
composable instead.Loading Globally
If you'd like to avoid loading the analytics in development, you can use the Environment overrides in your Nuxt config.
export default defineNuxtConfig({
scripts: {
registry: {
googleTagManager: {
id: '<YOUR_ID>'
}
}
}
})
useScriptGoogleTagManager
The useScriptGoogleTagManager
composable lets you have fine-grain control over when and how Google Tag Manager is loaded on your site.
const { proxy } = useScriptGoogleTagManager({
id: 'YOUR_ID' // id is only needed if you haven't configured globally
})
// example
proxy.dataLayer.push({ event: 'conversion', value: 1 })
Please follow the Registry Scripts guide to learn more about proxy
.
Guide: Sending Page Events
If you'd like to manually send page events to Google Tag Manager, you can use the proxy
with the useScriptEventPage composable.
This composable will trigger the provided function on route change after the page title has been updated.
const { proxy } = useScriptGoogleTagManager({
id: 'YOUR_ID' // id is only needed if you haven't configured globally
})
useScriptEventPage((title, path) => {
// triggered on route change after title is updated
proxy.dataLayer.push({
event: 'pageview',
title,
path
})
})
GoogleTagManagerApi
interface GoogleTagManagerApi {
dataLayer: Record<string, any>[]
google_tag_manager: GoogleTagManager
}
Config Schema
You must provide the options when setting up the script for the first time.
export const GoogleTagManagerOptions = object({
/**
* The Google Tag Manager ID.
*/
id: string(),
/**
* The name of the dataLayer you want to use
* @default 'defaultGtm'
*/
dataLayerName: optional(string())
})
Example
Using Google Tag Manager only in production while using dataLayer
to send a conversion event.
<script setup lang="ts">
const { dataLayer } = useScriptGoogleTagManager()
// noop in development, ssr
// just works in production, client
dataLayer.push({ event: 'conversion-step', value: 1 })
function sendConversion() {
dataLayer.push({ event: 'conversion', value: 1 })
}
</script>
<template>
<div>
<button @click="sendConversion">
Send Conversion
</button>
</div>
</template>