Search code examples
vue.jsgoogle-tag-managernuxt.js

how to add gtm dataLayer to nuxt.js component?


I have a problem adding to dayaLayer. For gtm I use this plugin, but I don’t understand how to add dataLayer for it through the component. My nuxt.config fo plugin

modules: [
    ['@nuxtjs/google-tag-manager', {
      id: 'GTM-xxxxxxxxxx',
      pageViewEventName: 'nuxtRoute',
      pageTracking: true,
      layer: 'dataLayer'
    }]
  ]

My component

head() {
    return {
      title: this.seo.title_meta,
      meta: [
        // hid is used as unique identifier. Do not use `vmid` for it as it will not work
        { hid: 'google-site-verification', name: 'google-site-verification', content: 'test' },
        { hid: 'description', name: 'description', content: this.seo.description_meta }
      ],
      __dangerouslyDisableSanitizers: ['script'],
      script: [
        {
          innerHTML: JSON.stringify({
            '@context': 'http://schema.org',
            '@type': 'Organization',
            name: 'test',
            url: 'https://test.co',
            sameAs: this.linkMeta,
            description: `${this.seo.description_meta}`
          }),
          type: 'application/ld+json'
        },
        {
          innerHTML: `
            window.dataLayer = window.dataLayer || [];
            window.dataLayer = [{ 'pageType': 'Main'}]
          `
        }
      ]
    };
  },

I tried to add a script with dataLayer to the head but nothing came of it. My Google Tag Assistant plugin does not find dataLayer. Thanks for any help!


Solution

  • In your nuxt.config.js you need to add this to the head object:

    script: [
      {
        hid: 'gtm',
        innerHTML: `window.dataLayer = window.dataLayer || [];`,
        type: 'text/javascript'
      }
    ]
    

    Than in your nuxt pages you can use the mounted hook to push the data to the dataLayer like this:

    mounted: {
        window.dataLayer.push({variable: value, someOtherVar: anotherValue})
    }
    

    It's important to use the mounted hook as this one is called wenn asycData() or fetch() has finished and the app is hydrated and therefore window is available.