You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt.js动态生成FAQPage JSON-LD时机问题求助

Nuxt.js 动态生成FAQPage JSON-LD 结构化数据解决方案

核心思路

利用Nuxt内置的头部管理API(useHead/head()),在FAQ组件内直接注入符合规范的JSON-LD脚本,通过唯一标识确保不会生成重复的script标签,同时解决生命周期时机问题。


Nuxt 3 实现方案

在FAQ组件中使用useHead(组合式API),直接构建并注入JSON-LD脚本。useHead会被Nuxt的头部系统统一收集,在渲染时生成单个script标签,且时机早于页面完成钩子,不存在数据延迟问题。

<script setup>
// 接收父组件传入的动态FAQ数据(或自行请求获取)
const props = defineProps({
  faqItems: {
    type: Array,
    required: true,
    default: () => []
  }
})

// 构建并注入JSON-LD
useHead({
  script: [
    {
      type: 'application/ld+json',
      // 序列化符合Google规范的FAQPage结构
      innerHTML: JSON.stringify({
        "@context": "https://schema.org",
        "@type": "FAQPage",
        "mainEntity": props.faqItems.map(item => ({
          "@type": "Question",
          "name": item.question,
          "acceptedAnswer": {
            "@type": "Answer",
            "text": item.answer
          }
        }))
      }),
      // 唯一key:确保重复渲染时替换而非新增script标签
      key: 'faq-jsonld'
    }
  ]
})
</script>

<template>
  <!-- FAQ组件的UI渲染 -->
  <div class="faq-container">
    <div v-for="(item, index) in faqItems" :key="index" class="faq-item">
      <h3>{{ item.question }}</h3>
      <p>{{ item.answer }}</p>
    </div>
  </div>
</template>

Nuxt 2 实现方案

使用Nuxt 2的head()选项API,同样通过唯一hid属性避免重复script标签,动态数据直接从组件data/props中获取。

<template>
  <div class="faq-container">
    <div v-for="(item, index) in faqItems" :key="index" class="faq-item">
      <h3>{{ item.question }}</h3>
      <p>{{ item.answer }}</p>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    faqItems: {
      type: Array,
      required: true,
      default: () => []
    }
  },
  head() {
    return {
      script: [
        {
          type: 'application/ld+json',
          innerHTML: JSON.stringify({
            "@context": "https://schema.org",
            "@type": "FAQPage",
            "mainEntity": this.faqItems.map(item => ({
              "@type": "Question",
              "name": item.question,
              "acceptedAnswer": {
                "@type": "Answer",
                "text": item.answer
              }
            }))
          }),
          // 唯一hid:Nuxt会根据该值合并重复的头部内容
          hid: 'faq-jsonld'
        }
      ]
    }
  }
}
</script>

关键注意事项

  • 避免重复标签:必须给script设置唯一的key(Nuxt3)或hid(Nuxt2),Nuxt会自动合并相同标识的脚本,不会生成多个script标签。
  • 动态数据兼容性:无论是props传入还是异步请求获取的FAQ数据,只要是响应式的,useHead/head()会自动更新脚本内容(Nuxt3支持响应式数据自动更新,Nuxt2需手动触发$nuxt.$router.app.$forceUpdate()或使用watch监听数据变化后更新head)。
  • SSR友好:该方案在SSR模式下会直接在服务器端生成JSON-LD脚本,爬虫无需等待客户端渲染即可抓取,完全符合Google富文本搜索的要求。

内容的提问来源于stack exchange,提问作者Nixx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 09:45:11