首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在nuxt.js组件中添加gtm dataLayer?

如何在nuxt.js组件中添加gtm dataLayer?
EN

Stack Overflow用户
提问于 2020-01-23 22:29:13
回答 1查看 2.8K关注 0票数 3

我在添加到dayaLayer时遇到问题。对于gtm,我使用这个plugin,但我不知道如何通过组件为它添加dataLayer。我的nuxt.config fo插件

代码语言:javascript
运行
复制
modules: [
    ['@nuxtjs/google-tag-manager', {
      id: 'GTM-xxxxxxxxxx',
      pageViewEventName: 'nuxtRoute',
      pageTracking: true,
      layer: 'dataLayer'
    }]
  ]

我的组件

代码语言:javascript
运行
复制
head() {
    return {
      title: this.seo.title_meta,
      meta: [
        // hid is used as unique identifier. Do not use `vmid` for it as it will not work
        { hid: 'google-site-verification', name: 'google-site-verification', content: 'test' },
        { hid: 'description', name: 'description', content: this.seo.description_meta }
      ],
      __dangerouslyDisableSanitizers: ['script'],
      script: [
        {
          innerHTML: JSON.stringify({
            '@context': 'http://schema.org',
            '@type': 'Organization',
            name: 'test',
            url: 'https://test.co',
            sameAs: this.linkMeta,
            description: `${this.seo.description_meta}`
          }),
          type: 'application/ld+json'
        },
        {
          innerHTML: `
            window.dataLayer = window.dataLayer || [];
            window.dataLayer = [{ 'pageType': 'Main'}]
          `
        }
      ]
    };
  },

我试图添加一个带有dataLayer的脚本,但是没有结果。我的谷歌标签助手插件找不到dataLayer。谢谢你的帮助!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-17 17:35:48

在您的nuxt.config.js中,您需要将以下内容添加到head对象:

代码语言:javascript
运行
复制
script: [
  {
    hid: 'gtm',
    innerHTML: `window.dataLayer = window.dataLayer || [];`,
    type: 'text/javascript'
  }
]

在nuxt页面中,您可以使用挂载的钩子将数据推送到dataLayer,如下所示:

代码语言:javascript
运行
复制
mounted: {
    window.dataLayer.push({variable: value, someOtherVar: anotherValue})
}

使用挂载的钩子很重要,因为这个钩子名为wenn,asycData()或fetch()已经完成,应用程序是水合的,因此窗口是可用的。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59880855

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档