[英]VueJS - How to pass Axios response data from parent to child component?
[英]How to pass data from axios response from parent to child in Vue
我正在对我的视图级别(父级)进行 axios 调用,并根据返回的数据,将其分配给 ref() 变量。 然后我想将这个变量作为道具传递给我的子组件。
父母
<template>
<User_List :users="uniqueNames"/>
</template>
<script setup lang="ts">
import User_List from "@/components/User/User_list.vue"
import { useRoute } from 'vue-router'
import { ref, onMounted } from 'vue'
import { api } from "@/api"
import { UserNameSurname } from "@/interfaces/user"
import { useNotification } from "@kyvg/vue3-notification";
import router from '@/router';
const { notify } = useNotification()
const route = useRoute()
const uniqueNames = ref<UserNameSurname>([])
const get_unique_users = async (phrase: string) =>{
await api
.post("users/find_unique_users", {phrase: phrase})
.then(response => {
uniqueNames.value = response.data
})
.catch(error => {
notify({
title: "Błąd",
text: error.response.data.detail,
type: "warn",
duration: 3000
});
router.push("/")
})
}
onMounted(() => {
const phrase = route.params.phrase
get_unique_users(phrase)
})
</script>
孩子:
<template>
<div>this is user list {{props.users}}</div>
</template>
<script setup lang="ts">
import { UserNameSurname } from '@/interfaces/user';
const props = defineProps<{users: UserNameSurname}>()
</script>
问题是我的子组件将其视为undefined
。 看起来组件在实际调用之前就已安装。 我怎样才能克服它?
<template>
<div v-if="loading">Loading..</div>
<User_List v-else :users="uniqueNames"/>
</template>
<script setup lang="ts">
import User_List from "@/components/User/User_list.vue"
import { useRoute } from 'vue-router'
import { ref, onMounted } from 'vue'
import { api } from "@/api"
import { UserNameSurname } from "@/interfaces/user"
import { useNotification } from "@kyvg/vue3-notification";
import router from '@/router';
const { notify } = useNotification()
const route = useRoute()
const uniqueNames = ref<UserNameSurname>([])
const loading = ref(false)
const get_unique_users = async (phrase: string) =>{
await api
.post("users/find_unique_users", {phrase: phrase})
.then(response => {
uniqueNames.value = response.data
})
.catch(error => {
notify({
title: "Błąd",
text: error.response.data.detail,
type: "warn",
duration: 3000
});
router.push("/")
})
}
onMounted(async () => {
loading.value = true;
const phrase = route.params.phrase
await get_unique_users(phrase)
loading.value = false;
})
</script>
users
属性的变化
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.