首页 > 解决方案 > 如何在 Nuxt 中添加“文本/javascript”

问题描述

我必须在<head>标签中添加以下脚本。但在 Nuxt 中,我必须将其作为 objext 添加到 nuxt.config.js 中。

我该怎么做呢?

<script type="text/javascript">
  /* To enable Participant Auto Authentication, uncomment this code below (https://docs.growsurf.com/getting-started/participant-auto-authentication) */
  /*
  window.grsfConfig = {
    email: "participant@email.com",// Replace this with the participant's email address
    hash: "HASH_VALUE" // Replace this with the SHA-256 HMAC value
  };
  */
  (function(g,r,s,f){g.grsfSettings={campaignId:"mpw47p",version:"2.0.0"};s=r.getElementsByTagName("head")[0];f=r.createElement("script");f.async=1;f.src="https://app.growsurf.com/growsurf.js"+"?v="+g.grsfSettings.version;f.setAttribute("grsf-campaign", g.grsfSettings.campaignId);!g.grsfInit?s.appendChild(f):"";})(window,document);
</script>

标签: nuxt.js

解决方案


Nuxt 的正确方法是为 GrowSurf 创建自己的插件(请参阅nuxt 插件文档)。

首先,在一个新文件中创建你的插件plugins/growsurf.js

/* eslint-disable */

export default ({ app }) => {
  /*
   ** Only run on client-side and only in production mode
   */
  if (process.env.NODE_ENV !== 'production') {
    return;
  }

  /* To enable Participant Auto Authentication, uncomment this code below (https://docs.growsurf.com/getting-started/participant-auto-authentication) */
  /*
  window.grsfConfig = {
    email: "participant@email.com",// Replace this with the participant's email address
    hash: "HASH_VALUE" // Replace this with the SHA-256 HMAC value
  };
  */
  (function(g,r,s,f){g.grsfSettings={campaignId:"mpw47p",version:"2.0.0"};s=r.getElementsByTagName("head")[0];f=r.createElement("script");f.async=1;f.src="https://app.growsurf.com/growsurf.js"+"?v="+g.grsfSettings.version;f.setAttribute("grsf-campaign", g.grsfSettings.campaignId);!g.grsfInit?s.appendChild(f):"";})(window,document);

}

然后告诉 Nuxt 在你的主应用程序中导入它:

// nuxt.config.js

export default {
  plugins: [{ src: '~plugins/growsurf.js', mode: 'client' }]
}

此外,您可以在 Nuxt 官方常见问题解答中找到类似的 Google Analytics 示例:https ://nuxtjs.org/faq/ga


推荐阅读