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

Vue3 Composition API:如何用API返回的JSON初始化对象数组?

问题分析与解决方法

你遇到的console.log(streams.value)返回undefined,核心原因是fetch是异步操作——你把打印代码写在了fetch调用的外面,此时请求还未完成、数据还没赋值给streams,自然打印出undefined。另外,streams作为对象数组,建议明确类型并初始化为空数组,避免类型模糊和模板遍历报错。

修正方案1:优化then链式写法

<script setup lang="ts">
import { ref, onMounted } from "vue";

// 定义Stream类型,明确数组元素结构
interface Stream {
  marketId: string | number;
  timeframe: string;
}
// 初始化为空数组,保证类型安全
const streams = ref<Stream[]>([]);

onMounted(() => {
  fetch("http://localhost:3000/stream")
    .then((response) => response.json())
    .then((result) => {
      streams.value = result;
      console.log(streams.value); // 请求完成后再打印,就能拿到数据
    })
    .catch((err) => {
      // 务必添加错误捕获,处理请求失败场景
      console.error("数据请求失败:", err);
    });
});
</script>

修正方案2:使用async/await(更推荐,代码可读性更高)

<script setup lang="ts">
import { ref, onMounted } from "vue";

interface Stream {
  marketId: string | number;
  timeframe: string;
}
const streams = ref<Stream[]>([]);

// onMounted回调标记为async,内部使用await处理异步
onMounted(async () => {
  try {
    const response = await fetch("http://localhost:3000/stream");
    const result = await response.json();
    streams.value = result;
    console.log(streams.value); // 此时数据已完成赋值
  } catch (err) {
    console.error("数据请求失败:", err);
  }
});
</script>

额外说明

  • 初始化为ref([])而非ref():即使请求未返回,streams也是空数组,模板中遍历(比如v-for)时不会因"undefined不是数组"报错。
  • 定义TS接口Stream:让类型检查更严格,避免后续操作中出现类型不匹配的问题。
  • 错误捕获:网络请求可能失败,必须添加错误处理逻辑,提升页面稳定性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 19:20:35