vue-gtag

repository·master·Indexed 21 days ago

https://github.com/matteogabriele/vue-gtag

A 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.

Tokens
6.3K
Snippets
26
Records
33
Agent score
75%

What's inside vue-gtag

  1. Initialize vue-gtag in a Vue application

    master

    To 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');
  2. Configure Google Analytics tracking with GtagConfigParams

    master

    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;
    };
  3. Configure the vue-gtag plugin settings

    master

    The Settings type defines the configuration object used when initializing the vue-gtag plugin. Key configuration areas include:

    • Core Identity: tagId (required) is your primary Google Tag Manager or Google Analytics ID. groupName (default: "default") sets the analytics group name.
    • Script Loading: The 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).
    • Data Layer & API: Customize the global variable names using dataLayerName (default: "dataLayer") and gtagName (default: "gtag").
    • Initialization Mode: 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).
    • Consent & Accounts: consentMode sets the initial state to 'denied' or 'granted'. additionalAccounts allows tracking multiple tagIds alongside the primary one.
  4. Configure automatic route tracking with PageTracker

    master

    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

  5. Manage Google Consent Mode with consent()

    master

    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_data
    • ad_personalization
    • ad_storage
    • analytics_storage
    import { consent } from 'vue-gtag';
    
    // Example: Updating consent status
    consent('update', {
      ad_user_data: 'granted',
      ad_personalization: 'granted',
      ad_storage: 'granted',
      analytics_storage: 'granted',
    });
  6. Manage vue-gtag plugin settings

    master

    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();
  7. Access the $gtag API in Vue components

    master

    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 settings
    • consent: Consent management (consent, consentDeniedAll, consentGrantedAll)
    • customMap: Custom mapping utilities
    • ecommerce: Ecommerce tracking
    • event: Event tracking
    • exception: Exception tracking
    • linker: Cross-domain linking
    • optIn / optOut: Opt-in/out management
    • pageview: Page view tracking
    • screenview: Screen view tracking
    • set: Set parameters
    • time: Time-based tracking
    • query: Query parameters
    // Example usage in a Vue component (Options API)
    export default {
      mounted() {
        this.$gtag.event({
          event_name: 'component_mounted',
          params: { method: 'mounted' }
        });
      }
    }
  8. Opt in to tracking with optIn()

    master

    Use optIn() to enable Google Analytics tracking.

    • If called without arguments, it enables tracking for the primary tagId and all additionalAccounts configured in the plugin settings.
    • If a specific 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');
  9. Manage user consent with consent, consentGrantedAll, and consentDeniedAll

    master

    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' 
    });