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

如何将Storyblok SEO数据接入Nuxt应用?解决读取seo属性报错问题

解决Storyblok + Nuxt中useServerSeoMeta的500错误

问题原因

你遇到的Cannot read properties of undefined (reading 'seo')错误,本质是访问了未定义的属性:要么story请求失败为空,要么story.content里没有seo字段,或者字段未正确初始化。

解决方案

1. 添加空值保护(可选链操作符)

直接在访问属性时使用?.可选链,避免因某个层级为空导致崩溃,同时设置默认值作为兜底:

<script setup>
const { slug } = useRoute().params
const runtimeConfig = useRuntimeConfig()
const resolveRelations = ['ProductGroup.products']
 
const story = await useAsyncStoryblok(
  slug && slug.length > 0 ? slug.join('/') : 'home',
  { 
    version: runtimeConfig.STORYBLOK_CONTENT_VERSION,
    resolve_relations: resolveRelations,
  },
)

useServerSeoMeta({
  // 用可选链逐层检查,为空时返回默认标题
  title: () => story?.content?.seo?.title || '我的网站',
  // 其他SEO字段同理处理
  metaDescription: () => story?.content?.seo?.description || '网站默认描述',
})
</script>
 
<template>
  <StoryblokComponent v-if="story" :blok="story.content" class="mx-3"/>
</template>

2. 捕获请求异常

如果useAsyncStoryblok请求失败(比如slug无效、API密钥错误),会导致story为空,添加try/catch可以主动处理错误:

<script setup>
const { slug } = useRoute().params
const runtimeConfig = useRuntimeConfig()
const resolveRelations = ['ProductGroup.products']

let story = null
try {
  story = await useAsyncStoryblok(
    slug && slug.length > 0 ? slug.join('/') : 'home',
    { 
      version: runtimeConfig.STORYBLOK_CONTENT_VERSION,
      resolve_relations: resolveRelations,
    },
  )
} catch (err) {
  console.error('获取Storyblok内容失败:', err)
}

useServerSeoMeta({
  title: () => story?.content?.seo?.title || '默认标题',
})
</script>
 
<template>
  <StoryblokComponent v-if="story" :blok="story.content" class="mx-3"/>
</template>

3. 验证Storyblok内容结构

登录Storyblok后台,确认你当前使用的页面模板中确实添加了SEO字段,并且所有需要渲染SEO的页面都已填写该字段。如果部分页面未设置SEO,默认值会确保页面不会崩溃。

额外说明

你之前尝试的useAsyncData不需要单独使用,因为useAsyncStoryblok已经封装了useAsyncData的异步逻辑,直接在await之后处理数据即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 17:22:49