Nuxt Nation 大会即将到来。加入我们,时间为 11 月 12 日至 13 日。

nuxt-gtm
@zadigetvoltaire/nuxt-gtm

一个用于 Google Tag Manager 的 Nuxt 模块

Nuxt GTM

npm versionnpm downloadsLicenseNuxt

Nuxt Google Tag Manager 模块与 Nuxt Devtools 集成,适用于 Nuxt 3。

此库是 @gtm-support/vue-gtm 插件的 Nuxt 3 模块包装器

快速设置

  1. @zadigetvoltaire/nuxt-gtm 依赖项添加到您的项目中
# Using pnpm
pnpm add -D @zadigetvoltaire/nuxt-gtm

# Using yarn
yarn add --dev @zadigetvoltaire/nuxt-gtm

# Using npm
npm install --save-dev @zadigetvoltaire/nuxt-gtm
  1. @zadigetvoltaire/nuxt-gtm 添加到 nuxt.config.tsmodules 部分
export default defineNuxtConfig({
  modules: [
    '@zadigetvoltaire/nuxt-gtm'
  ],
})
  1. nuxtConfig.gtmnuxtConfig.runtimeConfig.public.gtm 中添加配置

此模块支持两种配置方式

  • 直接在 Nuxt 配置的 gtm 键中
  • 在公共 runtimeConfig 中:用于使用环境变量覆盖配置并处理多个环境
export default defineNuxtConfig({
  ...
  gtm: {
    id: 'GTM-xxxxxx', // Your GTM single container ID, array of container ids ['GTM-xxxxxx', 'GTM-yyyyyy'] or array of objects [{id: 'GTM-xxxxxx', queryParams: { gtm_auth: 'abc123', gtm_preview: 'env-4', gtm_cookies_win: 'x'}}, {id: 'GTM-yyyyyy', queryParams: {gtm_auth: 'abc234', gtm_preview: 'env-5', gtm_cookies_win: 'x'}}], // Your GTM single container ID or array of container ids ['GTM-xxxxxx', 'GTM-yyyyyy']
    queryParams: {
      // Add URL query string when loading gtm.js with GTM ID (required when using custom environments)
      gtm_auth: 'AB7cDEf3GHIjkl-MnOP8qr',
      gtm_preview: 'env-4',
      gtm_cookies_win: 'x',
    },
    defer: false, // Script can be set to `defer` to speed up page load at the cost of less accurate results (in case visitor leaves before script is loaded, which is unlikely but possible). Defaults to false, so the script is loaded `async` by default
    compatibility: false, // Will add `async` and `defer` to the script tag to not block requests for old browsers that do not support `async`
    nonce: '2726c7f26c', // Will add `nonce` to the script tag
    enabled: true, // defaults to true. Plugin can be disabled by setting this to false for Ex: enabled: !!GDPR_Cookie (optional)
    debug: true, // Whether or not display console logs debugs (optional)
    loadScript: true, // Whether or not to load the GTM Script (Helpful if you are including GTM manually, but need the dataLayer functionality in your components) (optional)
    enableRouterSync: true, // Pass the router instance of your app to automatically sync with router (optional)
    ignoredViews: ['homepage'], // Don't trigger events for specified router names (optional)
    trackOnNextTick: false, // Whether or not call trackView in Vue.nextTick
    devtools: true, // (optional)
  }
  ...
  runtimeConfig: {
    public: {
      gtm: {
        id: 'GTM-xxxxxx',
        queryParams: {
          gtm_auth: 'AB7cDEf3GHIjkl-MnOP8qr',
          gtm_preview: 'env-4',
          gtm_cookies_win: 'x',
        },
        defer: false,
        compatibility: false,
        nonce: '2726c7f26c',
        enabled: true,
        debug: true,
        loadScript: true,
        enableRouterSync: true,
        ignoredViews: ['homepage'],
        trackOnNextTick: false,
        devtools: true,
      }
    }
  }
})

文档

请参考 @gtm-support/vue-gtm 文档

组合式 API - useGtm 可组合函数

示例

<template>
  <button @click="triggerEvent">
    Trigger event!
  </button>
  <button @click="triggerView">
    Trigger event!
  </button>
</template>

<script lang="ts" setup>
  const gtm = useGtm() // auto-imported by the module

  function triggerEvent() {
    gtm.trackEvent({
      event: 'event name',
      category: 'category',
      action: 'click',
      label: 'My custom component trigger',
      value: 5000,
      noninteraction: false,
    })
  }

  function triggerView() {
    gtm.trackView('Home', '/')
  }
</script>

选项 API

export default {
  methods: {
    triggerEvent() {
      this.$gtm.trackEvent({
        event: 'event name',
        category: 'category',
        action: 'click',
        label: 'My custom component trigger',
        value: 5000,
        noninteraction: false,
      })
    }
  }
}

模块选项

模块继承了插件 @gtm-support/vue-gtm 的选项,除了 vueRouter 条目被 enableRouterSync 替换。

type ModuleOptions = {
  // SPECIFIC MODULES OPTIONS
  /**
   * Enable Nuxt Devtools integration
   *
   * @default true
   */
  devtools?: boolean
  /**
   * Synchronise GTM with NuxtRouter
   */
  enableRouterSync?: boolean

  // PLUGIN AND MODULE OPTIONS

  /**
   * Derive additional event data after navigation.
   */
  vueRouterAdditionalEventData?: (to: RouteLocationNormalized, from: RouteLocationNormalized) => Record<string, any> | Promise<Record<string, any>>;
  /**
   * Don't trigger events for specified router names.
   */
  ignoredViews?: string[] | ((to: RouteLocationNormalized, from: RouteLocationNormalized) => boolean);
  /**
   * Whether or not call `trackView` in `Vue.nextTick`.
   */
  trackOnNextTick?: boolean;
  /**
   * Your GTM single container ID, array of container ids or array of objects.
   *
   * @example
   *     'GTM-xxxxxx'
   *     // or
   *     ['GTM-xxxxxx', 'GTM-yyyyyy']
   *     // or
   *     [{
   *       id: 'GTM-xxxxxx',
   *       queryParams: {
   *         gtm_auth: 'abc123',
   *         gtm_preview: 'env-4',
   *         gtm_cookies_win: 'x'
   *       }
   *     }, {
   *       id: 'GTM-yyyyyy',
   *       queryParams: {
   *         gtm_auth: 'abc234',
   *         gtm_preview: 'env-5',
   *         gtm_cookies_win: 'x'
   *       }
   *     }]
   */
  id: string | string[] | GtmIdContainer[];
  /**
   * Add url query string when load gtm.js with GTM ID.
   */
  queryParams?: GtmQueryParams;
  /**
   * Script can be set to `defer` to speed up page load at the cost of less accurate results (in case visitor leaves before script is loaded, which is unlikely but possible).
   *
   * Defaults to false, so the script is loaded `async` by default.
   *
   * @default false
   */
  defer?: boolean;
  /**
   * Will add `async` and `defer` to the script tag to not block requests for old browsers that do not support `async`.
   *
   * @default false
   */
  compatibility?: boolean;
  /**
   * Will add `nonce` to the script tag.
   *
   * @see [Using Google Tag Manager with a Content Security Policy](https://developers.google.com/tag-manager/web/csp)
   */
  nonce?: string;
  /**
   * The URL of the script; useful for server-side GTM.
   *
   * @default https://127.0.0.1/gtm.js
   */
  source?: string;
  /**
   * Plugin can be disabled by setting this to `false`.
   *
   * @example enabled: !!GDPR_Cookie
   * @default true
   */
  enabled?: boolean;
  /**
   * Whether or not to display console logs debugs.
   */
  debug?: boolean;
  /**
   * Whether or not to load the GTM Script.
   *
   * Helpful if you are including GTM manually, but need the dataLayer functionality in your components.
   */
  loadScript?: boolean;
  /**
   * The property of Track view event.
   *
   * @example trackViewEventProperty: 'track-view-event-demo'
   * @default content-view
   */
  trackViewEventProperty?: string;
}

就是这样!您现在可以在您的 Nuxt 应用中使用 Nuxt GTM ✨

贡献

# Install dependencies, prepare apps & run dev server
make start

# Run dev server
pnpm dev

# Develop with playground, with bundled client ui
pnpm play:prod

# Run ESLint
pnpm lint

# Run Vitest
pnpm test
pnpm test:watch

发布新版本

  1. 执行发布命令

⚠ 此命令应仅在主分支上执行

此命令将

  • 生成 CHANGELOG.md 并将其与发布提交一起推送
  • 更新包版本
  • 创建并推送新标签
  • 创建一个 github 发布以触发库发布管道
pnpm release

© Zadig&Voltaire 是 ZV FRANCE 的注册商标