Nuxt.js 中的条件模块加载 [英] Conditional module loading in Nuxt.js

查看:120
本文介绍了Nuxt.js 中的条件模块加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Nuxt.js 配置中有一个用于 Google 标签管理器的模块,如下所示:

I have a module for Google Tag Manager in my Nuxt.js config, like so:

modules: [
  [
    '@nuxtjs/google-tag-manager',
    {
      id: 'GTM-XXXXXXX'
    }
  ]
]

这工作正常,但我想知道如何根据站点设置的 cookie 值有条件地加载此模块?

This is working fine but I am wondering how I can conditionally load this module based on the value of a cookie set by the site?

我们有一种机制,用户可以通过这种机制选择接受或拒绝某些 cookie,其中一部分是阻止跟踪脚本.

We have a mechanism by which the user can select certain cookies to accept or deny and a part of that is to block tracking scripts.

对于通过配置加载的模块或脚本,有没有推荐的方法来做到这一点?理想情况下,如果将来 cookie 中的值也发生变化,则可以加载这些内容.

Is there any recommended way to do this with modules or scripts loaded via the config? Ideally, it would be possible to then load these should the values within the cookies change in the future as well.

非常感谢任何帮助或指示.

Any help or pointers are greatly appreciated.

推荐答案

要有条件地执行 GTM,您必须删除 @nuxtjs/google-tag-manager 并将其作为插件自己实现.NUXT 文档真的很棒,你也有介绍过.我使用了这个资源来实现,最后得到了这个代码:

To execute GTM conditionally you have to drop the @nuxtjs/google-tag-manager and implement it yourself as a plugin. NUXT docs are really awesome and have you covered on this too. I used this resource for implementation and ended up with this code:

// app/plugins/gtm.js

import Cookies from 'js-cookie'

const gtmKey = 'GTM-XXXXX' // <- insert your GTM key here

export default () => {
  /*
  ** Only run on client-side and only in production mode
  */
  if (process.env.NODE_ENV !== 'production') return
  /*
  ** Only run if it's not prevented by user
  */
  if (Cookies.get('disable-gtm')) return
  /*
  ** Include Google Tag Manager
  */
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
      new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
    j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
    'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
  })(window,document,'script','dataLayer', gtmKey)
}

基本上,您允许用户设置自定义 cookie(在我的情况下为 disable-gtm)并在 gtm.js 插件中检查此 cookie.如果存在且有效,请跳过与 GTM 相关的所有内容.

Basically you allow the user to set a custom cookie (disable-gtm in my case) and check this cookie in the gtm.js plugin. If it's there and valid, skip everything GTM related.

这篇关于Nuxt.js 中的条件模块加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆