Nuxt 3中无法从指定API获取并展示数据,求解决方法
Nuxt3 useFetch调用API报错的解决方法
问题原因
你遇到的「500 Cannot read properties of null (reading 'name')」错误有两个核心原因:
- API返回结构差异:jsonplaceholder的API直接返回数组,而目标API返回的是包含
data字段的对象(实际店铺数组在res.data里),你原代码直接把整个响应对象当作数组循环,自然无法获取shop.name。 - 异步数据加载时机:
useFetch是异步请求,初始状态下shops为null,模板直接循环null会触发属性读取错误。
修正方案
方案一:在请求时转换响应数据(推荐)
通过useFetch的transform选项提取数组,同时设置默认值避免初始null:
<template> <ul> <li v-for="shop in shops" :key="shop.id"> {{ shop.name }} </li> </ul> </template> <script setup> const { data: shops } = await useFetch('https://mocki.io/v1/3fa1924f-6c6b-4d49-b9ec-d91f6da13c3c', { // 转换响应数据,提取内部的data数组,为空时返回空数组 transform: (response) => response.data || [] }) </script>
方案二:在模板中处理结构与空值
直接在模板中通过可选链和空值合并,访问正确的数组字段并处理初始null:
<template> <ul> <!-- 先判断shops是否存在,再取data数组,为空时用空数组兜底 --> <li v-for="shop in shops?.data || []" :key="shop.id"> {{ shop.name }} </li> </ul> </template> <script setup> const { data: shops } = await useFetch('https://mocki.io/v1/3fa1924f-6c6b-4d49-b9ec-d91f6da13c3c') </script>
内容的提问来源于stack exchange,提问作者curiousmike
相关产品推荐
相关产品推荐

