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

Ruu*_*Pul 4 json-ld vue.js vuejs3

当尝试将 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>
Run Code Online (Sandbox Code Playgroud)

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

ton*_*y19 17

解决方法是使用 Vue 的内置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>
Run Code Online (Sandbox Code Playgroud)

演示

在此输入图像描述