MatteoGabriele / vue-gtag

Global Site Tag plugin for Vue (gtag.js)
https://matteo-gabriele.gitbook.io/vue-gtag/
MIT License
864 stars 64 forks source link

NuxtJs - Call Plugin in another plugin - vue-gtag #288

Closed mBbkr closed 3 years ago

mBbkr commented 3 years ago

I have integrated a vue-gtag component for NuxtJs in a plugin :

I'm looking for how to call the $gtag global var instantiate by the gtag component, in another component.

In the target plugin I've tried :

export default ({ app, env, $gtag }) => {
....
}

or :

export default ({ app, env, gtag }) => {
....
}

or :

export default ({ env, app: {gtag} }) => {
....
}

It's always undefined.

Somebody have an idea how to do that ?

gtag-plugin.client.js

import Vue from 'vue'
import VueGtag from 'vue-gtag'

export default ({ app, env }) => {   

  Vue.use(VueGtag, {
    config: { env.gaIdProd },
    bootstrap: getGDPR === 'true',
    appName: 'xxx',
    enabled: getGDPR === 'true',
    pageTrackerScreenviewEnabled: true
  }, app.router)
}
MatteoGabriele commented 3 years ago

you can find it in the component scope like most plugins:

<template>
  <div>
    <button @click="track">Track</button>
  </div>
</template>

<script>
export default {
  name: 'MyComponent',

  methods: {
    track () {
      this.$gtag.pageview('/foo')
    }
  }
}
</script>
mBbkr commented 3 years ago

I already know that. This is not what I'm looking for.

I'm not in a .vue i'm in a dot js for a plugin. this is where i need $gtag.

MatteoGabriele commented 3 years ago
import { pageview } from 'vue-gtag'

pageview('/foo')
MatteoGabriele commented 3 years ago

if you want to use all gtag feature, you can import the query method: it would be like calling gtag itself

Coinhexa commented 1 month ago

@m8bkr I found a solution to this problem What is the order of your plugin initialization? Your vue-gtag.client.js and vue-gtag.server.js must come before the plugin that wants to access app.$gtag else it will always be undefined