乐闻世界logo
搜索文章和话题

How to use gtag.js with nuxtjs ?

1个答案

1

In projects built with Nuxt.js, integrating Google Analytics (via gtag.js) involves several key steps. I will provide a detailed explanation of each step and offer a concrete example to help you understand the entire process.

Step 1: Create or Obtain Your Google Analytics Tracking ID

First, you must have a Google Analytics account. After logging into your account, create a new property to obtain a tracking ID (typically formatted as UA-XXXXX... or G-XXXXXXXXXX).

Step 2: Install the Nuxt.js Google Analytics Module

To integrate Google Analytics more conveniently into your Nuxt.js project, use the dedicated module @nuxtjs/google-analytics. Install it in your Nuxt.js project:

bash
npm install @nuxtjs/google-analytics

Step 3: Configure nuxt.config.js

In the nuxt.config.js file, configure the @nuxtjs/google-analytics module. This is the critical section for integrating Google Analytics into your project. Specify your tracking ID:

javascript
export default { modules: [ ['@nuxtjs/google-analytics', { id: 'UA-XXXXX...-X' // Replace with your actual Google Analytics tracking ID }] ], }

Step 4: Configure Tracking Options (Optional)

In the module configuration above, set additional tracking options, such as disabling tracking in development mode:

javascript
export default { modules: [ ['@nuxtjs/google-analytics', { id: 'UA-XXXXX...-X', dev: false // Do not send data to Google Analytics in development mode }] ], }

Step 5: Verify and Test

Once deployed, monitor user activity in the Real-Time reports section of Google Analytics to confirm data collection. During local testing, verify that requests to Google Analytics are being sent.

Example

Consider a Nuxt.js project where you want to track user visits to specific pages. After implementing the steps above, whenever a user visits any page, the page view is automatically recorded in Google Analytics. You can view page views and visitor data in the 'Behavior' section of Google Analytics.

By following this approach, you can easily integrate gtag.js into your Nuxt.js project to effectively track and analyze your website traffic and user behavior.

2024年7月31日 00:31 回复

你的答案