### Install vue-gtag with npm
Source: https://github.com/matteogabriele/vue-gtag/blob/master/README.md
Use this command to install the vue-gtag package via npm. Ensure you have Node.js and npm installed.
```bash
npm install vue-gtag
```
--------------------------------
### Using $gtag in Vue Components (Setup API)
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
Access the global `$gtag` property within Vue components using the setup API to perform tracking actions like sending events or managing e-commerce transactions.
```typescript
```
--------------------------------
### Direct Access to gtag API with query
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
The `query` function allows direct interaction with the underlying gtag API for advanced configurations and custom events. It supports operations like 'config', 'event', 'get', 'js', and 'set'.
```typescript
import { query } from 'vue-gtag';
// Direct gtag config call
query('config', 'G-XXXXXXXXXX', {
send_page_view: false,
debug_mode: true
});
// Direct event call
query('event', 'custom_event', {
custom_param: 'value'
});
// Get client ID
query('get', 'G-XXXXXXXXXX', 'client_id', (clientId) => {
console.log('Client ID:', clientId);
});
// Get session ID
query('get', 'G-XXXXXXXXXX', 'session_id', (sessionId) => {
console.log('Session ID:', sessionId);
});
// Initialize timestamp
query('js', new Date());
// Set linker directly
query('set', 'linker', {
domains: ['example.com'],
accept_incoming: true
});
```
--------------------------------
### Configuration API
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
APIs for updating runtime configuration and defining custom parameters.
```APIDOC
## config - Update Runtime Configuration
### Description
Updates the Google Analytics configuration at runtime for all configured tag IDs.
### Method
`config(options)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **options** (object) - Required - An object containing configuration options to update.
- **page_title** (string) - Optional - Updates the page title.
- **page_path** (string) - Optional - Updates the page path.
- **send_page_view** (boolean) - Optional - Controls whether to send page view events.
- **user_id** (string) - Optional - Sets the user ID for tracking.
- **user_properties** (object) - Optional - Sets custom user properties.
- **session_duration** (number) - Optional - Configures session duration in seconds.
- **cookie_expires** (number) - Optional - Configures cookie expiration in seconds.
### Request Example
```json
{
"page_title": "Updated Page Title",
"user_id": "USER-12345"
}
```
### Response
None
## customMap - Define Custom Dimensions and Metrics
### Description
Maps custom parameter names to Google Analytics custom dimensions and metrics.
### Method
`customMap(mapping)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **mapping** (object) - Required - An object where keys are GA parameter names (e.g., `dimension1`, `metric1`) and values are the custom parameter names.
### Request Example
```json
{
"dimension1": "user_type",
"metric1": "engagement_score"
}
```
### Response
None
## set - Set Global Parameters
### Description
Sets persistent values that will be included with all subsequent tracking calls.
### Method
`set(key, value)` or `set(parameters)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **key** (string) - Required - The parameter key to set (e.g., 'user_id', 'user_properties', 'campaign', 'developer_id').
- **value** (any) - Required - The value for the parameter. Can be a string, number, object, or array depending on the key.
- **parameters** (object) - Required - An object containing multiple key-value pairs to set globally.
### Request Example
```json
{
"user_id": "USER-12345"
}
```
```json
{
"user_properties": {
"account_type": "premium"
}
}
```
```json
{
"campaign": {
"id": "spring_sale",
"source": "newsletter"
}
}
```
### Response
None
## linker - Configure Cross-Domain Tracking
### Description
Configures cross-domain measurement to track users across multiple domains.
### Method
`linker(options)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **options** (object) - Required - An object containing linker configuration.
- **domains** (array of strings) - Required - A list of domains to track across.
- **accept_incoming** (boolean) - Optional - Whether to accept incoming linker parameters.
- **decorate_forms** (boolean) - Optional - Whether to decorate form submissions.
- **url_position** (string) - Optional - The position of the URL parameter ('query' or 'fragment').
### Request Example
```json
{
"domains": ["example.com", "shop.example.com"],
"decorate_forms": true
}
```
### Response
None
```
--------------------------------
### Configure Cross-Domain Tracking with `linker`
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
Configure cross-domain measurement using the `linker` function to track users across multiple domains. It supports specifying domains, accepting incoming links, decorating forms, and URL position.
```typescript
import { linker } from 'vue-gtag';
// Basic cross-domain configuration
linker({
domains: ['example.com', 'shop.example.com', 'blog.example.com']
});
// Full configuration
linker({
domains: ['example.com', 'partner-site.com'],
accept_incoming: true,
decorate_forms: true,
url_position: 'query'
});
```
--------------------------------
### Initialize Vue Plugin with createGtag
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
Use createGtag to initialize the Google Analytics gtag instance as a Vue plugin. This makes the $gtag API globally available. Configure tag IDs, page view settings, additional accounts, and route tracking options. It also supports script loading hooks and router tracking hooks.
```typescript
import { createApp } from 'vue';
import { createGtag } from 'vue-gtag';
import { createRouter, createWebHistory } from 'vue-router';
import App from './App.vue';
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', name: 'Home', component: () => import('./views/Home.vue') },
{ path: '/about', name: 'About', component: () => import('./views/About.vue') },
{ path: '/products/:id', name: 'Product', component: () => import('./views/Product.vue') }
]
});
const app = createApp(App);
app.use(createGtag({
tagId: 'G-XXXXXXXXXX',
config: {
send_page_view: false,
cookie_domain: 'auto'
},
additionalAccounts: [
{ tagId: 'AW-XXXXXXXXXX', config: { send_page_view: false } }
],
pageTracker: {
router,
useScreenview: false,
sendPageView: true,
useRouteFullPath: true,
exclude: [
{ path: '/admin' },
{ name: 'PrivatePage' }
]
},
resource: {
url: 'https://www.googletagmanager.com/gtag/js',
inject: true,
preconnect: true,
defer: false
},
hooks: {
'script:loaded': () => console.log('GA script loaded'),
'script:error': (error) => console.error('GA script failed:', error),
'router:track:before': (route) => console.log('Tracking:', route.path),
'router:track:after': (route) => console.log('Tracked:', route.path)
}
}));
app.use(router);
app.mount('#app');
```
--------------------------------
### Using $gtag in Vue Components
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
When using `createGtag`, all tracking methods are available via the `$gtag` global property in Vue components.
```APIDOC
## Using $gtag in Vue Components
### Description
When using `createGtag`, all tracking methods are available via the `$gtag` global property in Vue components.
### Composition API Usage
```typescript
```
### Options API Usage
```typescript
```
```
--------------------------------
### Configure Standalone Google Analytics
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
Use the configure function for standalone Google Analytics configuration without Vue's plugin system. This is useful for manual initialization or with the useConsent composable. It supports manual init mode and consent management.
```typescript
import { configure, addGtag } from 'vue-gtag';
// Configure with manual initialization mode
configure({
tagId: 'G-XXXXXXXXXX',
initMode: 'manual',
consentMode: 'denied',
config: {
send_page_view: false
}
});
// Later, when user grants consent
async function onUserConsent() {
await addGtag();
console.log('Analytics initialized after consent');
}
```
--------------------------------
### Set Global Parameters with `set`
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
The `set` function establishes persistent values for all subsequent tracking calls. It can set user IDs, user properties, campaign data, and developer IDs.
```typescript
import { set } from 'vue-gtag';
// Set user ID globally
set({ user_id: 'USER-12345' });
// Set user properties
set('user_properties', {
account_type: 'premium',
signup_date: '2024-01-15'
});
// Set custom campaign data
set('campaign', {
id: 'spring_sale',
source: 'newsletter',
medium: 'email',
name: 'Spring Sale 2024'
});
// Set developer ID (for platforms)
set('developer_id', 'dMTAwNz');
```
--------------------------------
### Timing Event Tracking API
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
The `time` function tracks user timing data for performance measurement using the `timing_complete` event.
```APIDOC
## time - Track Timing Events
### Description
Tracks user timing data for performance measurement using the `timing_complete` event.
### Method
`time`
### Parameters
- **timing_params** (object) - Required - An object containing timing details.
- **event_category** (string) - Required - The category of the timing event (e.g., 'Performance', 'API', 'Vue Component').
- **event_label** (string) - Required - The label for the timing event (e.g., 'Page Load', URL, Component Name).
- **value** (number) - Required - The timing value in milliseconds.
### Request Example
```javascript
import { time } from 'vue-gtag';
// Track page load time
// window.addEventListener('load', () => {
// const loadTime = performance.now();
// time({
// event_category: 'Performance',
// event_label: 'Page Load',
// value: Math.round(loadTime)
// });
// });
// Track API response time
// async function fetchWithTiming(url) {
// const start = performance.now();
// const response = await fetch(url);
// const duration = performance.now() - start;
// time({
// event_category: 'API',
// event_label: url,
// value: Math.round(duration)
// });
// return response;
// }
// Track component render time
// import { onMounted } from 'vue';
// const startTime = performance.now();
// onMounted(() => {
// time({
// event_category: 'Vue Component',
// event_label: 'ProductList',
// value: Math.round(performance.now() - startTime)
// });
// });
```
### Response
This function does not return a value. It sends data to Google Analytics.
```
--------------------------------
### Manage Consent Preferences with `consent`
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
Use the `consent` function to manage user consent for data collection purposes. It accepts 'default' or 'update' actions and an object defining storage types. Supports region-specific settings.
```typescript
import { consent, consentGrantedAll, consentDeniedAll } from 'vue-gtag';
// Set default consent (before user interaction)
consent('default', {
ad_storage: 'denied',
ad_user_data: 'denied',
ad_personalization: 'denied',
analytics_storage: 'denied',
functionality_storage: 'granted',
personalization_storage: 'denied',
security_storage: 'granted',
wait_for_update: 500
});
// Update consent after user accepts all
consent('update', {
ad_storage: 'granted',
ad_user_data: 'granted',
ad_personalization: 'granted',
analytics_storage: 'granted'
});
// Partial consent (analytics only)
consent('update', {
analytics_storage: 'granted',
ad_storage: 'denied',
ad_user_data: 'denied',
ad_personalization: 'denied'
});
// Grant all consent with helper
consentGrantedAll('update');
// Deny all consent with helper
consentDeniedAll('update');
// Region-specific consent
consent('default', {
analytics_storage: 'denied',
ad_storage: 'denied',
region: ['EU', 'GB', 'CA']
});
```
--------------------------------
### Track Screen Views with vue-gtag
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
Use the `screenview` function to track screen views, suitable for mobile-style applications. It can accept simple screen names, configuration objects, or Vue Router route objects.
```typescript
import { screenview } from 'vue-gtag';
// Simple screen name
screenview('HomeScreen');
```
```typescript
// With app name
screenview({
app_name: 'MyVueApp',
screen_name: 'ProductListScreen'
});
```
```typescript
// Track Vue Router route as screen
import { useRoute } from 'vue-router';
const route = useRoute();
screenview(route); // Uses route.name or route.path as screen_name
```
--------------------------------
### Track Timing Events with vue-gtag
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
Use the `time` function to track user timing data for performance measurement. It sends `timing_complete` events and can be used for page load, API response, or component render times.
```typescript
import { time } from 'vue-gtag';
// Track page load time
window.addEventListener('load', () => {
const loadTime = performance.now();
time({
event_category: 'Performance',
event_label: 'Page Load',
value: Math.round(loadTime)
});
});
```
```typescript
// Track API response time
async function fetchWithTiming(url: string) {
const start = performance.now();
const response = await fetch(url);
const duration = performance.now() - start;
time({
event_category: 'API',
event_label: url,
value: Math.round(duration)
});
return response;
}
```
```typescript
// Track component render time
import { onMounted } from 'vue';
const startTime = performance.now();
onMounted(() => {
time({
event_category: 'Vue Component',
event_label: 'ProductList',
value: Math.round(performance.now() - startTime)
});
});
```
--------------------------------
### Track E-commerce Events with vue-gtag
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
Use the `ecommerce` function to track various e-commerce events. Ensure the correct event name and payload are provided for accurate data collection. This function requires importing `ecommerce` from 'vue-gtag'.
```typescript
import { ecommerce } from 'vue-gtag';
// View item list (category page)
ecommerce('view_item_list', {
item_list_id: 'category_shoes',
item_list_name: 'Shoes Collection',
items: [
{
item_id: 'SKU-001',
item_name: 'Running Shoe Pro',
item_brand: 'SportBrand',
item_category: 'Footwear',
item_category2: 'Running',
price: 129.99,
index: 0
},
{
item_id: 'SKU-002',
item_name: 'Trail Runner Elite',
item_brand: 'SportBrand',
item_category: 'Footwear',
item_category2: 'Trail',
price: 149.99,
index: 1
}
]
});
// View single item (product page)
ecommerce('view_item', {
currency: 'USD',
value: 129.99,
items: [{
item_id: 'SKU-001',
item_name: 'Running Shoe Pro',
item_brand: 'SportBrand',
item_category: 'Footwear',
item_variant: 'Blue / Size 10',
price: 129.99,
quantity: 1
}]
});
// Add to cart
ecommerce('add_to_cart', {
currency: 'USD',
value: 129.99,
items: [{
item_id: 'SKU-001',
item_name: 'Running Shoe Pro',
item_brand: 'SportBrand',
item_variant: 'Blue / Size 10',
price: 129.99,
quantity: 1
}]
});
// Remove from cart
ecommerce('remove_from_cart', {
currency: 'USD',
value: 129.99,
items: [{
item_id: 'SKU-001',
item_name: 'Running Shoe Pro',
price: 129.99,
quantity: 1
}]
});
// View cart
ecommerce('view_cart', {
currency: 'USD',
value: 279.98,
items: [
{ item_id: 'SKU-001', item_name: 'Running Shoe Pro', price: 129.99, quantity: 1 },
{ item_id: 'SKU-002', item_name: 'Trail Runner Elite', price: 149.99, quantity: 1 }
]
});
// Begin checkout
ecommerce('begin_checkout', {
currency: 'USD',
value: 279.98,
coupon: 'SUMMER20',
items: [
{ item_id: 'SKU-001', item_name: 'Running Shoe Pro', price: 129.99, quantity: 1 },
{ item_id: 'SKU-002', item_name: 'Trail Runner Elite', price: 149.99, quantity: 1 }
]
});
// Add shipping info
ecommerce('add_shipping_info', {
currency: 'USD',
value: 279.98,
coupon: 'SUMMER20',
shipping_tier: 'Express',
items: [
{ item_id: 'SKU-001', item_name: 'Running Shoe Pro', price: 129.99, quantity: 1 },
{ item_id: 'SKU-002', item_name: 'Trail Runner Elite', price: 149.99, quantity: 1 }
]
});
// Add payment info
ecommerce('add_payment_info', {
currency: 'USD',
value: 279.98,
coupon: 'SUMMER20',
payment_type: 'Credit Card',
items: [
{ item_id: 'SKU-001', item_name: 'Running Shoe Pro', price: 129.99, quantity: 1 },
{ item_id: 'SKU-002', item_name: 'Trail Runner Elite', price: 149.99, quantity: 1 }
]
});
// Purchase (conversion)
ecommerce('purchase', {
transaction_id: 'TXN-12345',
value: 304.97,
tax: 24.99,
shipping: 9.99,
currency: 'USD',
coupon: 'SUMMER20',
items: [
{ item_id: 'SKU-001', item_name: 'Running Shoe Pro', price: 129.99, quantity: 1 },
{ item_id: 'SKU-002', item_name: 'Trail Runner Elite', price: 149.99, quantity: 1 }
]
});
// Refund
ecommerce('refund', {
transaction_id: 'TXN-12345',
value: 129.99,
currency: 'USD',
items: [
{ item_id: 'SKU-001', item_name: 'Running Shoe Pro', price: 129.99, quantity: 1 }
]
});
// Promotion tracking
ecommerce('view_promotion', {
creative_name: 'Summer Sale Banner',
creative_slot: 'homepage_hero',
promotion_id: 'PROMO-SUMMER',
promotion_name: 'Summer Sale 2024',
items: [
{ item_id: 'SKU-001', item_name: 'Running Shoe Pro', promotion_name: 'Summer Sale' }
]
});
ecommerce('select_promotion', {
creative_name: 'Summer Sale Banner',
creative_slot: 'homepage_hero',
promotion_id: 'PROMO-SUMMER',
promotion_name: 'Summer Sale 2024'
});
```
--------------------------------
### Screen View Tracking API
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
The `screenview` function tracks screen views for mobile-style applications, useful when using mobile-first design patterns or hybrid apps.
```APIDOC
## screenview - Track Screen Views
### Description
Tracks screen views for mobile-style applications.
### Method
`screenview`
### Parameters
- **screen_name_or_config** (string | object) - Required - Can be a string representing the screen name or a configuration object.
- If string: The name of the screen to track.
- If object:
- **app_name** (string) - Optional - The name of the application.
- **screen_name** (string) - Required - The name of the screen to track.
### Request Example
```javascript
import { screenview } from 'vue-gtag';
import { useRoute } from 'vue-router';
// Simple screen name
screenview('HomeScreen');
// With app name
screenview({
app_name: 'MyVueApp',
screen_name: 'ProductListScreen'
});
// Track Vue Router route as screen
const route = useRoute();
screenview(route); // Uses route.name or route.path as screen_name
```
### Response
This function does not return a value. It sends data to Google Analytics.
```
--------------------------------
### Using $gtag in Vue Components (Options API)
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
In Vue components using the Options API, the `$gtag` instance is available via `this.$gtag` for tracking events, product views, and other analytics data.
```javascript
```
--------------------------------
### Update Runtime Configuration with `config`
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
The `config` function allows updating Google Analytics configuration at runtime for all tag IDs. Use it to modify page details, disable features, set user properties, or adjust session settings.
```typescript
import { config } from 'vue-gtag';
// Update page configuration
config({
page_title: 'Updated Page Title',
page_path: '/new-path'
});
// Disable page view on specific actions
config({
send_page_view: false
});
// Set user properties
config({
user_id: 'USER-12345',
user_properties: {
subscription_tier: 'premium',
account_type: 'business'
}
});
// Configure session settings
config({
session_duration: 1800,
cookie_expires: 63072000
});
```
--------------------------------
### Define Custom Dimensions and Metrics with `customMap`
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
Use `customMap` to map custom parameter names to Google Analytics custom dimensions and metrics. These mappings can then be used in `event` calls.
```typescript
import { customMap, event } from 'vue-gtag';
// Map custom parameters to dimensions
customMap({
dimension1: 'user_type',
dimension2: 'subscription_plan',
dimension3: 'experiment_variant',
metric1: 'engagement_score'
});
// Use custom dimensions in events
event('user_action', {
user_type: 'premium',
subscription_plan: 'annual',
experiment_variant: 'variant_b',
engagement_score: 85
});
```
--------------------------------
### Vue Composable for Consent Management with `useConsent`
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
The `useConsent` composable provides reactive consent management and cookie handling. It's designed for implementing cookie consent banners in Vue components. Ensure `initMode: 'manual'` is configured before use.
```typescript
Cookie Consent
We use cookies to improve your experience and analyze site usage.
Consent granted.
```
--------------------------------
### Consent Management API
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
APIs for managing user consent preferences, crucial for GDPR and privacy compliance.
```APIDOC
## consent - Set Consent Preferences
### Description
Manages user consent for various data collection purposes.
### Method
`consent(mode, preferences)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **mode** (string) - Required - The mode for consent update (e.g., 'default', 'update').
- **preferences** (object) - Required - An object containing consent preferences for different storage types (e.g., `ad_storage`, `analytics_storage`).
- **ad_storage** (string) - Optional - 'granted' or 'denied'.
- **ad_user_data** (string) - Optional - 'granted' or 'denied'.
- **ad_personalization** (string) - Optional - 'granted' or 'denied'.
- **analytics_storage** (string) - Optional - 'granted' or 'denied'.
- **functionality_storage** (string) - Optional - 'granted' or 'denied'.
- **personalization_storage** (string) - Optional - 'granted' or 'denied'.
- **security_storage** (string) - Optional - 'granted' or 'denied'.
- **wait_for_update** (number) - Optional - Delay in milliseconds before applying updates.
- **region** (array of strings) - Optional - Specifies regions for region-specific consent.
### Request Example
```json
{
"mode": "default",
"preferences": {
"ad_storage": "denied",
"analytics_storage": "granted",
"region": ["EU", "GB"]
}
}
```
### Response
None
## consentGrantedAll - Grant All Consent
### Description
Helper function to grant all consent preferences.
### Method
`consentGrantedAll(mode)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **mode** (string) - Required - The mode for consent update (e.g., 'update').
### Request Example
```json
{
"mode": "update"
}
```
### Response
None
## consentDeniedAll - Deny All Consent
### Description
Helper function to deny all consent preferences.
### Method
`consentDeniedAll(mode)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **mode** (string) - Required - The mode for consent update (e.g., 'update').
### Request Example
```json
{
"mode": "update"
}
```
### Response
None
## useConsent - Vue Composable for Consent Management
### Description
Provides reactive consent management and cookie handling within Vue components.
### Method
`useConsent()`
### Parameters
None
### Request Example
```html
Cookie Consent
Consent granted.
```
### Response
Returns an object with the following properties:
- **hasConsent** (boolean) - Indicates if consent has been granted.
- **acceptAll** (function) - Function to accept all consent preferences.
- **rejectAll** (function) - Function to reject all consent preferences.
- **acceptCustom** (function) - Function to accept custom consent preferences.
```
--------------------------------
### query - Direct gtag API Access
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
The `query` function provides direct access to the underlying gtag API for advanced use cases not covered by the higher-level functions.
```APIDOC
## query - Direct gtag API Access
### Description
The `query` function provides direct access to the underlying gtag API for advanced use cases not covered by the higher-level functions.
### Usage
```typescript
import { query } from 'vue-gtag';
// Direct gtag config call
query('config', 'G-XXXXXXXXXX', {
send_page_view: false,
debug_mode: true
});
// Direct event call
query('event', 'custom_event', {
custom_param: 'value'
});
// Get client ID
query('get', 'G-XXXXXXXXXX', 'client_id', (clientId) => {
console.log('Client ID:', clientId);
});
// Get session ID
query('get', 'G-XXXXXXXXXX', 'session_id', (sessionId) => {
console.log('Session ID:', sessionId);
});
// Initialize timestamp
query('js', new Date());
// Set linker directly
query('set', 'linker', {
domains: ['example.com'],
accept_incoming: true
});
```
```
--------------------------------
### Track Page Views with vue-gtag
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
Manually track page views using the `pageview` function. It accepts string paths, Vue Router route objects, or detailed configuration objects for UTM parameter extraction.
```typescript
import { pageview } from 'vue-gtag';
// Simple string path
pageview('/products/shoes');
```
```typescript
// Track with Vue Router route object
import { useRoute } from 'vue-router';
const route = useRoute();
pageview(route);
```
```typescript
// Detailed pageview configuration
pageview({
page_title: 'Product Details - Running Shoes',
page_path: '/products/running-shoes',
page_location: 'https://example.com/products/running-shoes?color=blue',
send_page_view: true
});
```
```typescript
// Virtual pageview for SPA modal
function openProductModal(productId: string) {
pageview({
page_title: `Product Modal - ${productId}`,
page_path: `/modal/product/${productId}`,
page_location: window.location.href
});
}
```
--------------------------------
### optOut / optIn - Disable or Enable Tracking
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
The `optOut` and `optIn` functions allow users to disable or re-enable Google Analytics tracking, useful for implementing "Do Not Track" preferences.
```APIDOC
## optOut / optIn - Disable or Enable Tracking
### Description
The `optOut` and `optIn` functions allow users to disable or re-enable Google Analytics tracking, useful for implementing "Do Not Track" preferences.
### Usage
```typescript
import { optOut, optIn, event } from 'vue-gtag';
// Disable all tracking
optOut();
// Events will not be sent while opted out
event('test_event'); // This won't be tracked
// Re-enable tracking
optIn();
// Now events will be sent again
event('tracking_resumed');
// Disable tracking for specific account only
optOut('G-SECONDARY');
// Re-enable specific account
optIn('G-SECONDARY');
// User preference implementation
function saveTrackingPreference(enabled: boolean) {
localStorage.setItem('analytics_enabled', String(enabled));
if (enabled) {
optIn();
} else {
optOut();
}
}
// Restore preference on page load
function restoreTrackingPreference() {
const enabled = localStorage.getItem('analytics_enabled') !== 'false';
if (!enabled) {
optOut();
}
}
```
```
--------------------------------
### Page View Tracking API
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
The `pageview` function manually tracks page views with support for string paths, Vue Router route objects, or detailed configuration objects.
```APIDOC
## pageview - Track Page Views
### Description
Manually tracks page views. Supports string paths, Vue Router route objects, or detailed configuration objects.
### Method
`pageview`
### Parameters
- **page_path_or_route_or_config** (string | object) - Required - Can be a string path, a Vue Router route object, or a configuration object.
- If string: The path of the page to track.
- If object (Vue Router route): The route object from `useRoute()`.
- If object (configuration):
- **page_title** (string) - Optional - The title of the page.
- **page_path** (string) - Optional - The path of the page.
- **page_location** (string) - Optional - The full URL of the page.
- **send_page_view** (boolean) - Optional - Whether to send the page view hit.
### Request Example
```javascript
import { pageview } from 'vue-gtag';
import { useRoute } from 'vue-router';
// Simple string path
pageview('/products/shoes');
// Track with Vue Router route object
const route = useRoute();
pageview(route);
// Detailed pageview configuration
pageview({
page_title: 'Product Details - Running Shoes',
page_path: '/products/running-shoes',
page_location: 'https://example.com/products/running-shoes?color=blue',
send_page_view: true
});
```
### Response
This function does not return a value. It sends data to Google Analytics.
```
--------------------------------
### Exception Tracking API
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
The `exception` function reports errors and exceptions to Google Analytics for monitoring application health.
```APIDOC
## exception - Track Errors and Exceptions
### Description
Reports errors and exceptions to Google Analytics for monitoring application health.
### Method
`exception`
### Parameters
- **exception_params** (object) - Required - An object containing exception details.
- **description** (string) - Optional - A description of the exception.
- **fatal** (boolean) - Optional - Indicates if the exception is fatal.
### Request Example
```javascript
import { exception } from 'vue-gtag';
// Basic exception tracking
exception({
description: 'API request failed',
fatal: false
});
// Vue error handler integration
// app.config.errorHandler = (err, instance, info) => {
// exception({
// description: `${err.message} | Component: ${instance?.$options.name} | Info: ${info}`,
// fatal: true
// });
// console.error(err);
// };
// Promise rejection handler
// window.addEventListener('unhandledrejection', (event) => {
// exception({
// description: `Unhandled Promise: ${event.reason}`,
// fatal: false
// });
// });
```
### Response
This function does not return a value. It sends data to Google Analytics.
```
--------------------------------
### Track Custom Events with vue-gtag
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
Use the `event` function to send custom events to Google Analytics. Supports standard and custom event names with optional parameters like category, label, value, and callbacks.
```typescript
import { event } from 'vue-gtag';
// Basic event tracking
event('button_click', {
event_category: 'engagement',
event_label: 'hero_cta',
value: 1
});
```
```typescript
// Form submission tracking
event('form_submit', {
event_category: 'lead_generation',
event_label: 'contact_form',
method: 'email'
});
```
```typescript
// Login tracking
event('login', {
method: 'Google'
});
```
```typescript
// Sign up tracking
event('sign_up', {
method: 'Email'
});
```
```typescript
// Search tracking
event('search', {
search_term: 'vue analytics'
});
```
```typescript
// Share tracking
event('share', {
method: 'Twitter',
content_type: 'article',
content_id: 'article-123'
});
```
```typescript
// Event with callback
event('file_download', {
event_category: 'downloads',
event_label: 'product_brochure.pdf',
event_callback: () => {
console.log('Download event sent');
},
event_timeout: 2000
});
```
```typescript
// Send to specific account
event('conversion', {
send_to: 'AW-XXXXXXXXXX/CONVERSION_ID',
value: 99.99,
currency: 'USD'
});
```
--------------------------------
### Track Errors and Exceptions with vue-gtag
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
The `exception` function reports errors and exceptions to Google Analytics. It can be integrated with Vue's error handler or used for promise rejections and API errors.
```typescript
import { exception } from 'vue-gtag';
// Basic exception tracking
exception({
description: 'API request failed',
fatal: false
});
```
```typescript
// Vue error handler integration
app.config.errorHandler = (err, instance, info) => {
exception({
description: `${err.message} | Component: ${instance?.$options.name} | Info: ${info}`,
fatal: true
});
console.error(err);
};
```
```typescript
// Promise rejection handler
window.addEventListener('unhandledrejection', (event) => {
exception({
description: `Unhandled Promise: ${event.reason}`,
fatal: false
});
});
```
```typescript
// API error tracking
async function fetchData() {
try {
const response = await fetch('/api/data');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (error) {
exception({
description: `API Error: ${error.message}`,
fatal: false
});
throw error;
}
}
```
--------------------------------
### Event Tracking API
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
The `event` function sends custom events to Google Analytics with optional parameters. It supports all standard Google Analytics event names and custom event names.
```APIDOC
## event - Track Custom Events
### Description
Sends custom events to Google Analytics with optional parameters. Supports standard and custom event names.
### Method
`event`
### Parameters
- **event_name** (string) - Required - The name of the event to track.
- **event_params** (object) - Optional - An object containing event parameters such as `event_category`, `event_label`, `value`, `event_callback`, `event_timeout`, `send_to`, `currency`, etc.
### Request Example
```javascript
import { event } from 'vue-gtag';
// Basic event tracking
event('button_click', {
event_category: 'engagement',
event_label: 'hero_cta',
value: 1
});
// Send to specific account
event('conversion', {
send_to: 'AW-XXXXXXXXXX/CONVERSION_ID',
value: 99.99,
currency: 'USD'
});
```
### Response
This function does not return a value. It sends data to Google Analytics.
```
--------------------------------
### Disable or Enable Google Analytics Tracking
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
Use `optOut` and `optIn` to manage user consent for tracking. These functions can also target specific Google Analytics accounts.
```typescript
import { optOut, optIn, event } from 'vue-gtag';
// Disable all tracking
optOut();
// Events will not be sent while opted out
event('test_event'); // This won't be tracked
// Re-enable tracking
optIn();
// Now events will be sent again
event('tracking_resumed');
// Disable tracking for specific account only
optOut('G-SECONDARY');
// Re-enable specific account
optIn('G-SECONDARY');
// User preference implementation
function saveTrackingPreference(enabled: boolean) {
localStorage.setItem('analytics_enabled', String(enabled));
if (enabled) {
optIn();
} else {
optOut();
}
}
// Restore preference on page load
function restoreTrackingPreference() {
const enabled = localStorage.getItem('analytics_enabled') !== 'false';
if (!enabled) {
optOut();
}
}
```
--------------------------------
### Manually Inject Google Analytics Script
Source: https://context7.com/matteogabriele/vue-gtag/llms.txt
The addGtag function manually injects the Google Analytics gtag script. It's typically used after user consent is granted when initMode is set to 'manual'. Supports deferred loading and nonce for CSP compliance.
```typescript
import { configure, addGtag, event } from 'vue-gtag';
// Initial setup with deferred loading
configure({
tagId: 'G-XXXXXXXXXX',
initMode: 'manual',
resource: {
inject: true,
preconnect: true,
defer: true,
nonce: 'abc123' // For CSP compliance
},
hooks: {
'script:loaded': () => {
event('analytics_initialized', { method: 'manual' });
}
}
});
// Call when ready to initialize
document.getElementById('accept-cookies')?.addEventListener('click', async () => {
await addGtag();
});
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.