Vue中父组件Axios响应数据传给子组件时显示undefined的解决方法
解决Vue子组件props因异步请求未完成显示undefined的问题
先修正父组件的类型错误
你的父组件中uniqueNames的泛型定义有误,应该指定为数组类型,确保初始值符合类型约束:
// 原代码 const uniqueNames = ref<UserNameSurname>([]) // 修改为 const uniqueNames = ref<UserNameSurname[]>([])
三种实用解决方法
方法1:父组件条件渲染子组件
通过v-if控制子组件的渲染时机,确保数据加载完成后再渲染子组件,避免传递未初始化的值:
<template> <!-- 当数组有内容时渲染子组件 --> <User_List :users="uniqueNames" v-if="uniqueNames.length"/> <!-- 可选:加载时显示占位内容 --> <div v-else>加载中...</div> </template>
方法2:子组件设置props默认值
让子组件的users props支持可选,并设置默认空数组,这样即使父组件数据未加载,子组件也能拿到合法的初始值:
// 子组件script部分 import { UserNameSurname } from '@/interfaces/user'; const props = withDefaults(defineProps<{ users?: UserNameSurname[] }>(), { users: () => [] })
子组件模板可保持原写法,此时会显示空数组而非undefined。
方法3:父组件添加加载状态优化体验
在父组件中新增加载状态变量,配合条件渲染给用户更清晰的反馈:
// 父组件script中添加状态 const isLoading = ref(true) const get_unique_users = async (phrase: string) =>{ try { const response = await api.post("users/find_unique_users", {phrase: phrase}) uniqueNames.value = response.data } catch (error) { notify({ title: "Błąd", text: error.response.data.detail, type: "warn", duration: 3000 }); router.push("/") } finally { isLoading.value = false } }
模板中使用状态控制渲染:
<template> <div v-if="isLoading">加载中...</div> <User_List :users="uniqueNames" v-else/> </template>
内容的提问来源于stack exchange,提问作者mathz
相关产品推荐
相关产品推荐

