Conditional module loading in Nuxt.js

你离开我真会死。 提交于 2020-02-21 13:27:11

问题


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

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

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?

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.

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.


回答1:


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)
}

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.



来源:https://stackoverflow.com/questions/54557966/conditional-module-loading-in-nuxt-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!