如何在NUXT 3中添加脚本块?

发布于 2025-02-12 18:59:18 字数 336 浏览 0 评论 0原文

我只想在head标签中添加脚本块。

示例

<script>
    alert('hello, world!');
</script>

我花了几个小时来找出一个简单的解决方案。 关于添加inline脚本有很多答案,但是脚本block nuxt 3

我们如何在nuxt中进行此操作3

I simply want to add a script block in the head tag.

Example

<script>
    alert('hello, world!');
</script>

I spent hours to figure out a solution for something as simple as this.
There are tons of answers about adding inline scripts, but none for the script block for Nuxt 3

How can we do this in Nuxt 3?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你在看孤独的风景 2025-02-19 18:59:18

好吧,我找到了答案。有3种可能的解决方案。

解决方案1 ​​

<template>
  <Script children="console.log('Hello, world!');" />
</template>

解决方案2

<script setup>
useHead({
  script: [{ children: "console.log('Hello, world!');" }],
});
</script>

解决方案3

import { defineNuxtConfig } from 'nuxt';

export default defineNuxtConfig({
  app: {
    head: {
      script: [{ children: "console.log('Hello, world!');" }],
    },
  },
});

Okay, I found the answer. There are 3 possible solutions.

Solution 1

<template>
  <Script children="console.log('Hello, world!');" />
</template>

Solution 2

<script setup>
useHead({
  script: [{ children: "console.log('Hello, world!');" }],
});
</script>

Solution 3

import { defineNuxtConfig } from 'nuxt';

export default defineNuxtConfig({
  app: {
    head: {
      script: [{ children: "console.log('Hello, world!');" }],
    },
  },
});
百变从容 2025-02-19 18:59:18

补充月亮的答案,还有另一种实现这一目标的方法。此方法允许您将其全球导入到应用程序中,并使您可以完全控制标签本身:

解决方案4

export default defineNuxtConfig({
    css: ['./public/assets/style.css', 'primeicons/primeicons.css'],
    app: {
        head: {
            script: [{
                src: "https://consent.cookiebot.com/uc.js",
                "data-cbid": "xxxxx",
                type: "text/javascript",
                id: "Cookiebot",
                async: true
            }]
        }
    }
})

此方法还可以与use> usehead({})函数一起使用您想将脚本添加到特定页面。

Complementing Moon's answer, there is another way to achieve this. This method allows you to import it globally into your app and gives you complete control over the tag itself:

Solution 4

export default defineNuxtConfig({
    css: ['./public/assets/style.css', 'primeicons/primeicons.css'],
    app: {
        head: {
            script: [{
                src: "https://consent.cookiebot.com/uc.js",
                "data-cbid": "xxxxx",
                type: "text/javascript",
                id: "Cookiebot",
                async: true
            }]
        }
    }
})

This approach also works with the useHead({}) function if you want to add a script to a specific page.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文