nuxt3接入google-analytics(谷歌分析)

1,180 阅读1分钟

环境

node: v20.12.2, 
"nuxt": "^3.11.2", 
"vue": "^3.4.27",
"nuxt-gtag": "^2.0.5",

安装

pnpm add nuxt-gtag -D

开发环境和生产环境区分

使用 .env 进行区分

开发环境的key

.env.development

# Google Analytics 的key
VITE_GTAG_ID = G-xxxxx

生产环境 .env.production

# Google Analytics 的key
VITE_GTAG_ID = G-kkkkk

已经定义好了开发环境和生产环境的 key

nuxt.config.ts 配置

export default defineNuxtConfig({
    modules: ['nuxt-gtag'],
    gtag: {
        id: import.meta.env.VITE_GTAG_ID,
    }
});

修改启动脚本

{
 "scripts": {
    "build": "nuxt build --dotenv .env.production",
    "dev": "nuxt dev --dotenv .env.development",
    "generate": "nuxt generate",
    "preview": "nuxt preview",
    "postinstall": "nuxt prepare"
  }
}

正常启动项目,查看 chrome 调试工具,network ,查看请求数据,应该会有这个记录 https://www.google-analytics.com/g/collect?

然后去 google analytics 的管理面板, 查看有数据进来,即接入成功

相关链接

如果会接入上面的,则,可能会使用到如下的相关工具

  1. 关键词分析/管理工具:
  1. 搜索引擎后台:
  1. 数据分析:Google Analyst