mib200 / vue-gtm

Simple implementation of Google Tag Manager in Vue.js 2.0
Apache License 2.0
242 stars 85 forks source link

Custom trackView dataLayer.push object #71

Closed dePablobernat closed 4 years ago

dePablobernat commented 4 years ago

I was trying to implement a custom tracking pageview event using vue-router, to try to use the router meta params to generate the custom object that I need to send to my data team.

Although I find out that I can't do that with the way is is coded right now.

So in order to fix that, my suggestion would be to change the trackView method from what it is right now

trackView(screenName, path) {
    if (inBrowser && pluginConfig.enabled) {
      logDebug('Dispatching TrackView', { screenName, path })
      let dataLayer = (window.dataLayer = window.dataLayer || [])
      dataLayer.push({
        event: 'content-view',
        'content-name': path,
        'content-view-name': screenName
      })
    }
  }

to something like:

trackView(screenName, path, options = {}) {
    if (inBrowser && pluginConfig.enabled) {
      logDebug('Dispatching TrackView', { screenName, path })
      let dataLayer = (window.dataLayer = window.dataLayer || [])
      dataLayer.push({
        event: 'content-view',
        'content-name': path,
        'content-view-name': screenName,
        ...options
      })
    }
  }

That way at least if we want to send trackView events on the router change we can use it like this:

this.$gtm.trackView('Home', '/home-page', { action: 'page-view', category: 'Home' .... })

And if we want to make that trackview Event automátic, we could change the way we are using the router meta params:

// Dispatch vue event using meta gtm value if defined otherwise fallback to route name
    const name = to.meta.gtmName || to.name
    const options = to.meta.gtm || {}
    const baseUrl = vueRouter.options.base || '';
    if (trackOnNextTick) {
      Vue.nextTick(() => {
        Vue.gtm.trackView(name, `${baseUrl}${to.fullPath}`, options)
      })
    } else {
      Vue.gtm.trackView(name, `${baseUrl}${to.fullPath}`, options)
    }

Then in your meta params you could set the gtm property like an object

meta: {
 gtmName: '',
 gtm: {
  action: '',
  category: '',
 ...
 }
}

If it's something you are willing to do I would submit a PR aswell so everyone can use it.

Thanks

Shinigami92 commented 4 years ago

Added in https://github.com/mib200/vue-gtm/commit/7d835b40984b5cacde07457b622314971453d28a