MatteoGabriele / vue-gtag-next

Global Site Tag plugin for Vue 3 (gtag.js)
MIT License
44 stars 3 forks source link

Use with Nuxt 3 + Vue 3 #42

Open drusellers opened 1 year ago

drusellers commented 1 year ago

Description

After following the instructions in the documentation, and the documentation of Nuxt 3, I have configured this plugin like so.

~/plugins/googleAnalytics.js

import VueGtag from 'vue-gtag-next'

export default defineNuxtPlugin((nuxtApp) => {
  const config = useRuntimeConfig()
  nuxtApp.vueApp.use(VueGtag, {
    property: {
      id: config.public.googleAnalyticsId,
    },
  })
})

Expected behavior

There should be no warnings in the terminal

Actual behavior

[Vue warn]: A plugin must either be a function or an object with an "install" function.

shows up in the terminal

Environment

Run this command in the project folder and fill in their results:

npm ls vue-gtag-next:

npm ls vue-gtag-next
Circa.EndlessAisle.Display@ /Users/drusellers/dev/circa/endless-aisle/src/Circa.EndlessAisle.Display
└── vue-gtag-next@1.14.0

Then, specify:

  1. Operating system: Darwin and Ubuntu 20
  2. Browser and version: Brave 1.46.144

Reproducible Demo

... skipped

remihuigen commented 1 year ago

@drusellers try this 👇

import VueGtag from 'vue-gtag-next'
export default defineNuxtPlugin((nuxtApp) => {
  const config = useRuntimeConfig()
  nuxtApp.vueApp.use(VueGtag.default, {
    property: {
      id: config.public.googleAnalyticsId,
    },
  })
})

Actually, I would recommend some more changes:

  1. fetch gtag lib after hydration to limit your bundle size.
  2. Add the router to auto track page views
  3. expose VueGtag globally via provide (as $t)

which gives the following code

import { defineNuxtPlugin } from '#app'

export default defineNuxtPlugin((nuxtApp) => {
    const t = ref(null)
    onNuxtReady(async () => {

        const VueGtag = await import('vue-gtag-next')
        t.value = VueGtag

        nuxtApp.vueApp.use(VueGtag.default, {
        property: {
            id: nuxtApp.$config.public.googleAnalytics.id
        },
        appName: 'Voorbereidingsplatform Demo',
        isEnabled: false,
        useDebugger: nuxtApp.payload.config.public.mode !== 'prod',
        pageTrackerScreenviewEnabled: true,
        });

        VueGtag.trackRouter(useRouter())
        if (VueGtag) console.log('vue-gtag plugin installed')
    })
  return {
    provide: {
      t
    }
  }
});

I'm using using a composable useTracking() with some reusable functions, such as disable() and enable() for GDPR compliance