[英]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.