Nuxt 3如何从JSON文件获取站点头部数据?
在Nuxt 3中从JSON文件读取数据的正确方法
首先看你提供的JSON数据结构:
(以上为JSON中的数据)
你当前尝试通过api.title读取数据失败,代码如下:
<script setup> const { data: api } = await useFetch(useRuntimeConfig().public.home) useServerSeoMeta({ title: api.title, description: 'This is my amazing site, let me tell you all about it.', }) </script>
问题根源
从JSON结构能看到,title并非在根层级,而是嵌套在header对象里,直接用api.title自然无法读取到目标值。
正确实现方式
方式1:直接访问嵌套属性
调整代码,通过api.header.title访问目标值,同时加上可选链避免数据加载前的报错:
<script setup> const { data: api } = await useFetch(useRuntimeConfig().public.home) useServerSeoMeta({ title: api?.header?.title, description: 'This is my amazing site, let me tell you all about it.', }) </script>
方式2:解构嵌套数据(适合多次使用的场景)
如果需要频繁调用header下的内容,可以先解构数据:
<script setup> const { data: api } = await useFetch(useRuntimeConfig().public.home) const { header } = api || {} useServerSeoMeta({ title: header?.title, description: 'This is my amazing site, let me tell you all about it.', }) </script>
本地JSON文件的简化方案
如果你的JSON是本地静态文件,无需通过useFetch请求,直接导入即可:
<script setup> import siteData from '~/data/home.json' useServerSeoMeta({ title: siteData.header.title, description: 'This is my amazing site, let me tell you all about it.', }) </script>
内容的提问来源于stack exchange,提问作者Alexander Krupnitsky
相关产品推荐
相关产品推荐

