Bootstrap options

Choose how you want to initialise vue-gtag in your application

Out of the box the plugin will bootstrap itself downloading the library and creating an instance of the gtag object as soon as at least one ID is provided. In case a different way to initialise the plugin is needed, here a few examples.

Options first, bootstrap later

Disable the plugin and add all the options first

import { createApp } from "vue";
import App from "./App.vue";
import VueGtag from "vue-gtag-next";

const app = createApp(App);

app.use(VueGtag, {
  isEnabled: false,
  property: { id: "GA_MEASUREMENT_ID" },
});

app.mount("#app");

then once the user accepts the tracking wall policy, for example, you can enable it and start tracking

<template>
  <div>
    <button @click="enable">Enable</button>
  </div>
</template>

<script>
import { useState } from "vue-gtag-next";

export default {
  name: "MyComponent",

  setup() {
    const { isEnabled } = useState();
    const enable = () => {
      isEnabled.value = true;
    };

    return {
      enable
    };
  }
};
</script>

No options, bootstrap later

By default the plugin needs two things to automatically bootstrap: the isEnabled option needs to be true , which it is by default, and it needs at least one property object with an id

With this in mind you can simply install the the plugin empty

import { createApp } from "vue";
import App from "./App.vue";
import VueGtag from "vue-gtag-next";

const app = createApp(App);

app.use(VueGtag);

app.mount("#app");

and in when you need, you can pass your property and automatically bootstrap

<template>
  <div>
    <button @click="enable">Enable</button>
  </div>
</template>

<script>
import { useState } from "vue-gtag-next";

export default {
  name: "MyComponent",

  setup() {
    const { property } = useState();
    const enable = () => {
      property.value = {
        id: "UA-1234567-8"
      };
    };

    return {
      enable
    };
  }
};
</script>

Options API vs Composition API

Nothing really changes if you need to you the Options API, just apply the same logic inside your method object.

<template>
  <div>
    <button @click="enable">Enable</button>
  </div>
</template>

<script>
import { useState } from "vue-gtag-next";

export default {
  methods: {
    enable() {
      const { property } = useState();

      property.value = {
        id: "UA-1234567-8"
      };
    }
  }
};
</script>

The globalObjectNamevalue needs to be added during plugin installation, if needed, because it's the only moment where the object is created in the window scope

Last updated