如何将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
相关产品推荐
相关产品推荐

