如何将 json-ld 添加到 Vue 3?

How to add json-ld to Vue 3?

当尝试将 json-ld 脚本标记添加到传送到 HEAD 的部分时,Vue 3 编译器失败并出现此错误:

VueCompilerError: Tags with side effect (<script> and <style>) are ignored in client component templates.

模板:

<template>
  <teleport to="head">
    <script type="application/ld+json">
      {
        "@context": "https://schema.org",
        "@type": "WebSite",
        "url": "https://www.example.com/",
        "potentialAction": {
          "@type": "SearchAction",
          "target": "https://query.example.com/search?q={search_term_string}",
          "query-input": "required name=search_term_string"
        }
      }
    </script>
  </teleport>
  <div>
    Hello world!
  </div>
</template>

如何在不安装其他依赖项的情况下添加此 json-ld 标签?

解决方法是使用 Vue 的 built-in component(即 <component :is="'script'">)而不是 <script>:

<template>
  <teleport to="head">
    <component :is="'script'" type="application/ld+json">
      {
        "@context": "https://schema.org",
        "@type": "WebSite",
        "url": "https://www.example.com/",
        "potentialAction": {
          "@type": "SearchAction",
          "target": "https://query.example.com/search?q={search_term_string}",
          "query-input": "required name=search_term_string"
        }
      }
    </component>
  </teleport>
  <div>
    Hello world!
  </div>
</template>

demo