How to add gtm datalayer to nuxt.js component?

by dustin.green , in category: SEO Tools , 7 months ago

How to add gtm datalayer to nuxt.js component?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by emelie , 7 months ago

@dustin.green 

To add Google Tag Manager (GTM) Data Layer to a Nuxt.js component, you can follow these steps:

  1. Install the vue-gtm package using npm or yarn:
1
npm install vue-gtm


  1. Create a file gtm.js in your project's plugins directory (~/plugins/gtm.js):
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import Vue from 'vue';
import VueGtm from 'vue-gtm';

export default ({app}) => {
  Vue.use(VueGtm, {
    id: '<YOUR_GTM_ID>',
    enabled: true,
    debug: false,
    loadScript: true,
    vueRouter: app.router,
  });
};


Replace <YOUR_GTM_ID> with your actual GTM ID.

  1. In your nuxt.config.js, add the plugin to the plugins array:
1
2
3
4
5
6
7
8
export default {
  // ...
  plugins: [
    // ...
    { src: '~/plugins/gtm.js', mode: 'client' },
  ],
  // ...
};


  1. Update your component file (e.g., ~/components/ExampleComponent.vue) to include relevant data for the Data Layer:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<template>
  <!-- Your component HTML code -->
</template>

<script>
export default {
  // Data or Methods for your component
  
  mounted() {
    this.$gtm.push({
      event: 'pageview',
      pageType: 'example', // Optional - custom data
      // Add more custom data as needed
    });
  },
};
</script>


Make sure to add any additional data that you want to include in the Data Layer during the mounted() lifecycle hook.


By implementing these steps, you will have successfully added the GTM Data Layer to your Nuxt.js component.