Nuxt3 SSR问题求助:接口数据无法在页面源码中显示
问题排查与解决方案
核心问题分析
你的代码存在两个关键问题,导致SSR渲染后的页面源码无法显示数据:
- 重复定义响应式变量:同时在
setup的ref和data中定义了allCategory,SSR阶段会优先读取data中的空数组,客户端渲染时才会被setup里的数据覆盖,因此页面能显示但源码无内容。 useFetch用法不规范:没有利用Nuxt3中useFetch的SSR适配特性,手动fetch的写法未确保SSR阶段数据被正确获取并注入到页面。
修正后的代码示例
脚本部分(基础修正版)
export default defineComponent({ setup() { const apiUrl = useRuntimeConfig().public.apiURL; // 仅在setup中定义响应式变量,移除data中的重复定义 const allCategory = ref([]); // 修正useFetch:确保回调返回Promise,Nuxt会等待其完成用于SSR渲染 useFetch(async () => { try { const response = await fetch(`${apiUrl}/api/list-categories`); const data = await response.json(); allCategory.value = data.all_category; } catch (error) { console.error(error); } }); return { allCategory }; }, // 移除data选项,避免变量冲突 });
脚本部分(推荐简洁版)
export default defineComponent({ setup() { const { public: { apiURL } } = useRuntimeConfig(); // 直接使用useFetch返回的响应式数据,无需手动创建ref const { data: allCategory } = useFetch('/api/list-categories', { baseURL: apiURL, transform: (res) => res.all_category // 直接转换返回的数据结构 }); return { allCategory }; } });
模板部分(无需修改)
<div v-for="(categoryName, index) in allCategory" :key="index"> {{ categoryName.which_category }} </div>
关键说明
- 移除重复变量:Nuxt3推荐通过
setup管理响应式数据,避免同时使用data选项导致变量冲突,确保SSR阶段能正确读取数据。 - 规范
useFetch用法:useFetch是Nuxt3专为SSR设计的数据获取工具,会自动在服务器端执行并将数据注入页面源码。即使手动使用fetch,也要保证回调为异步函数,Nuxt会等待其完成后再进行SSR渲染。 - 验证效果:修改后重启Nuxt服务,查看页面源码(
view-source:localhost:3000),即可看到渲染后的分类内容。
内容的提问来源于stack exchange,提问作者Zahidul Islam
相关产品推荐
相关产品推荐

