Vue中fetch获取API数据后ref值为空,无法传递给其他组件
Vue中fetch获取数据后ref为空的问题解决
问题原因
你现在的console.log(Posts)是在组件初始化时同步执行的,而onMounted里的API请求是异步操作——代码执行到console.log时,请求还没完成,Posts.value还是初始的空数组,所以打印出来看起来是空的。
解决办法
1. 正确查看异步加载后的数据
把打印语句放到请求完成之后,或者监听Posts的变化:
<script setup> import { onMounted, ref, watch } from 'vue'; const Posts = ref([]); onMounted(async () => { const Url = 'https://jsonplaceholder.typicode.com/posts'; try { const response = await fetch(Url); if (!response.ok) { throw new Error(`Response status: ${response.status}`); } Posts.value = await response.json(); // 请求完成后再打印 console.log(Posts.value); } catch(e) { console.log(`Error: ${e}`); } }) // 或者用watch监听Posts的变化 watch(Posts, (newValue) => { if (newValue.length > 0) { console.log(newValue); } }, { deep: true }) </script>
2. 传递数据给子组件
直接通过props传递即可,因为Posts是响应式的ref,当数据更新后子组件会自动接收到最新值:
父组件模板:
<template> <ChildComponent :posts="Posts" /> </template>
子组件接收:
<script setup> const props = defineProps({ posts: { type: Array, default: () => [] } }) // 可以在子组件里用watch监听props的变化,或者直接在模板中使用 watch(() => props.posts, (newPosts) => { console.log('子组件收到的posts:', newPosts); }, { deep: true }) </script> <template> <div v-for="post in posts" :key="post.id"> <h3>{{ post.title }}</h3> <p>{{ post.body }}</p> </div> </template>
内容的提问来源于stack exchange,提问作者NewUser
相关产品推荐
相关产品推荐

