vue.jsvuejs3json-ld

How to add json-ld to Vue 3?


When trying to add a json-ld script tag to a section that gets teleported to the HEAD, the Vue 3 compiler fails with this error:

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

Template:

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

How can I add this json-ld tag without installing additional dependencies?


Solution

  • A workaround is to use Vue's built-in component (i.e., <component :is="'script'">) instead of <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

    enter image description here