nuxt-community / google-gtag-module

Enable google gtagjs for NuxtJs
MIT License
147 stars 27 forks source link

Use within a Nuxt plugin #46

Closed SteveEdson closed 3 years ago

SteveEdson commented 3 years ago

I'm trying to send events from within a plugin, where this and therefore this.$gtag isn't available. Is it possible to import it or use it some other way?

Here's my plugin code:

import Vue from 'vue';

Vue.prototype.$trackEvent = (category, action, label = null, value = null) => {
  console.log('event', { category, action, label, value });

  if('dataLayer' in window) {
    this.$gtag('event', action, {
      event_category: category,
      event_label: label,
      value: value,
    });
  }
};

I'm wanting to do it this way so I can have a single $trackEvent method which could then send to google, hotjar, the console or any other services etc

SteveEdson commented 3 years ago

Actually, I've just figured it out:


export default ({ app }, inject) => {
  inject('trackEvent',(category, action, label = null, value = null) => {
    if ('$gtag' in app) {
      try {
        app.$gtag('event', action, {
          event_category: category,
          event_label: label,
          value: value,
        });
      } catch (e) {
        console.error('e', e);
      }
    }
  });
};

Thanks