Install vue-gtag
masterTo use the Global Site Tag plugin for Vue, install the vue-gtag package via npm. This package requires Vue ^3.0.0.
npm install vue-gtagrepository·master·Indexed 21 days ago
https://github.com/matteogabriele/vue-gtagA Global Site Tag (gtag.js) plugin for Vue applications (requires Vue ^3.0.0). It enables sending event data to Google Analytics, Google Ads, and the Google Marketing Platform. The library provides a comprehensive API for tracking pageviews, screen views, custom events, and ecommerce actions, as well as tools for managing Google Consent Mode, cross-domain linking, and opt-in/out preferences. It includes the useConsent composable for reactive consent management and a createGtag function for plugin initialization.
To use the Global Site Tag plugin for Vue, install the vue-gtag package via npm. This package requires Vue ^3.0.0.
npm install vue-gtagTo use vue-gtag in your Vue application, use the createGtag function. This function accepts a PluginSettings object to configure the plugin and returns a function that installs the $gtag API onto your Vue application instance via app.use().
When you call createGtag, it immediately calls configure() with your settings. If your initMode is not set to manual, it will automatically trigger the loading of the Google Analytics script.
import { createApp } from 'vue';
import App from './App.vue';
import { createGtag } from 'vue-gtag';
const app = createApp(App);
app.use(createGtag({
// your PluginSettings here
}));
app.mount('#app');When using the config command, you can provide GtagConfigParams to control how page views are tracked and how the page is identified.
Available keys:
page_title?: string: The title of the page being tracked.page_location?: string: The full URL of the page being tracked.page_path?: string: The path of the page being tracked.send_page_view?: boolean: Whether to send a page view event automatically.export type GtagConfigParams = {
page_title?: string;
page_location?: string;
page_path?: string;
send_page_view?: boolean;
};The Settings type defines the configuration object used when initializing the vue-gtag plugin. Key configuration areas include:
tagId (required) is your primary Google Tag Manager or Google Analytics ID. groupName (default: "default") sets the analytics group name.resource object controls how gtag.js is loaded. You can specify a custom url, enable preconnect, use defer, provide a nonce for CSP, or toggle inject (default: true).dataLayerName (default: "dataLayer") and gtagName (default: "gtag").initMode determines when the script initializes. Use 'auto' (default) for immediate loading, or 'manual' to delay initialization until addGtag is called (useful for consent management).consentMode sets the initial state to 'denied' or 'granted'. additionalAccounts allows tracking multiple tagIds alongside the primary one.The pageTracker option enables automatic tracking of Vue Router navigation events.
Key Options:
router: The Vue Router instance to monitor.template: A custom template for generating events. It can be a Pageview or Screenview object, or a function (route: Route) => PageTrackerParams.useScreenview: If true, uses the screen_view event instead of the default page_view.exclude: Defines routes to ignore. Can be an array of objects with path or name, or a function (route: Route) => boolean that returns true to exclude.sendPageView: If false, prevents automatic page_view events on route changes (default: true).useRouterBasePath: Uses the router's base path in tracking.useRouteFullPath: Sets page_path to the route's fullPath instead of just path.Note: If using pageTracker, ensure you disable
The consent function allows you to manually set the consent state for specific Google Consent Mode parameters. It takes a consentArg (the mode, e.g., "default" or "update") and a params object containing the consent status for various storage and data categories.
Supported parameter keys in GtagConsentParams include:
ad_user_dataad_personalizationad_storageanalytics_storageimport { consent } from 'vue-gtag';
// Example: Updating consent status
consent('update', {
ad_user_data: 'granted',
ad_personalization: 'granted',
ad_storage: 'granted',
analytics_storage: 'granted',
});The useConsent composable provides a reactive way to access and manage consent state within Vue components.
import { useConsent } from 'vue-gtag';
// Inside a Vue setup function
const { consentState } = useConsent();The vue-gtag plugin maintains an internal configuration state. You can retrieve the current configuration, update specific parameters using a partial settings object, or reset the configuration to its default state. Updates are performed using a deep merge, meaning nested objects like resource will be merged rather than completely overwritten.
import { getSettings, updateSettings, resetSettings } from '@/core/settings';
// Retrieve current settings
const current = getSettings();
// Update specific settings (e.g., changing the dataLayer name)
updateSettings({ dataLayerName: 'customDataLayer' });
// Reset to default values
resetSettings();Once vue-gtag is installed using createGtag, the entire Google Analytics API is exposed on your Vue application instance as $gtag. This allows you to access various tracking capabilities directly within your components using this.$gtag (in Options API) or via the global properties.
The $gtag object contains the following functional modules:
config: Configuration settingsconsent: Consent management (consent, consentDeniedAll, consentGrantedAll)customMap: Custom mapping utilitiesecommerce: Ecommerce trackingevent: Event trackingexception: Exception trackinglinker: Cross-domain linkingoptIn / optOut: Opt-in/out managementpageview: Page view trackingscreenview: Screen view trackingset: Set parameterstime: Time-based trackingquery: Query parameters// Example usage in a Vue component (Options API)
export default {
mounted() {
this.$gtag.event({
event_name: 'component_mounted',
params: { method: 'mounted' }
});
}
}Use optIn() to enable Google Analytics tracking.
tagId and all additionalAccounts configured in the plugin settings.tagId is provided, it will only enable that specific account.This function works by removing the ga-disable-{tagId} property from the global window object. It is ignored if running in a server-side environment.
import { optIn } from 'vue-gtag';
// Enable tracking for all configured accounts
optIn();
// Enable tracking for a specific account only
optIn('G-XXXXXXXXXX');Use optIn and optOut to manage user preference for tracking.
import { optIn, optOut } from 'vue-gtag';
optIn();
optOut();Control Google Analytics consent modes using the following functions:
consent: Set specific consent states for different purposes.consentGrantedAll: Grant consent for all purposes.consentDeniedAll: Deny consent for all purposes.import { consent, consentGrantedAll, consentDeniedAll } from 'vue-gtag';
// Grant all
consentGrantedAll();
// Deny all
consentDeniedAll();
// Specific consent
consent({
'analytics_storage': 'granted',
'ad_storage': 'denied'
});