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

Nuxt3 useFetch的pick选项在数组场景下失效问题求助

问题分析与解决方案

你的问题核心在于pick选项的作用逻辑:

  • pick: ['title']是对整个响应的顶层数据对象提取指定属性,而非遍历数组中的每个元素提取属性。
  • 如果你的API返回的是数组格式(比如[{title: '黄山'}, {title: '泰山'}]),顶层数组本身没有title属性,因此pick会返回{title: undefined},导致模板无法渲染数据。

正确处理数组响应的方法

若要从数组的每个元素中提取title字段,需使用transform函数处理响应数据:

<template>
  <section>
    <div v-for="mountain in mountains" :key="mountain">{{mountain}}</div>
  </section>
</template>

<script setup>
const runtimeConfig = useRuntimeConfig()

const { data: mountains, pending, error, refresh } = await useFetch('/mountains',{
  baseURL: runtimeConfig.public.apiBase,
  // 遍历数组,提取每个元素的title
  transform: (response) => response.map(item => item.title)
})

console.log(mountains.value)
</script>

如果需要保留对象结构(每个元素为{title: 'xxx'}),可修改transform逻辑:

transform: (response) => response.map(item => ({ title: item.title }))

关于官方示例的说明

官方示例中使用pick: ['title']的场景,对应的API返回应为单个对象(比如{ title: '山脉列表', data: [...] }),此时pick可以正确提取顶层的title属性。当响应是数组时,必须用transform逐个处理元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:26:15