vue中父組件通過props向子組件傳遞數(shù)據(jù)但子組件接收不到解決辦法
問題:
父組件在掛載時(shí)向后端發(fā)起請(qǐng)求獲取數(shù)據(jù),然后將獲取到的數(shù)據(jù)傳遞給子組件,子組件想要在掛載時(shí)獲取數(shù)據(jù),獲取不到。
代碼示例:
//父組件
<template>
<div>
<HelloWorld :message="message"></HelloWorld>
</div>
</template>
<script setup>
import HelloWorld from "./components/HelloWorld.vue";
import { onMounted, ref } from "vue";
const message = ref("1");
onMounted(() => {
//模擬異步請(qǐng)求
setTimeout(() => {
message.value = "1312";
}, 0);
});
</script>
<style scoped></style>
//子組件
<template>
<div>{{message}}</div>
</template>
<script setup>
import { onMounted, defineProps } from "vue";
const props = defineProps(["message"]);
onMounted(() => {
console.log("傳遞過來的數(shù)據(jù)", props.message);
});
</script>
<style scoped></style>打印結(jié)果:props.message為空,為父組件message的初始值,但是子組件數(shù)據(jù)能渲染出來

原因分析:
父子組件的生命周期執(zhí)行順序如下:
加載數(shù)據(jù)渲染過程
- 父組件beforeCreate
- 父組件created
- 父組件beforeMount
- 子組件beforeCreate
- 子組件created
- 子組件beforeMount
- 子組件mounted
- 父組件mounted
更新渲染數(shù)據(jù)
- 父組件beforeUpdate
- 子組件beforeUpdate
- 子組件updated
- 父組件updated
銷毀組件數(shù)據(jù)過程
- 父組件beforeUnmount
- 子組件beforeUnmount
- 子組件unmounted
- 父組件unmounted
由上述加載數(shù)據(jù)渲染過程可知子組件的mounted是先于父組件的mounted,所以獲取不到異步請(qǐng)求后獲取到的數(shù)據(jù)
解決方法
方法一:使用v-if控制子組件渲染的時(shí)機(jī)
//父組件
<template>
<div>
<HelloWorld :message="message" v-if="isShow"></HelloWorld>
</div>
</template>
<script setup>
import HelloWorld from "./components/HelloWorld.vue";
import { onMounted, ref } from "vue";
const message = ref("1");
const isShow=ref(false);
onMounted(() => {
//模擬異步請(qǐng)求
setTimeout(() => {
message.value = "1312";
isShow.value=true;//獲取數(shù)據(jù)成功,再讓子組件渲染
}, 0);
});
</script>
<style scoped></style>
方法二:使用watch對(duì)父組件傳遞過來的數(shù)據(jù)進(jìn)行監(jiān)控
//子組件
<template>
<div>{{message}}</div>
</template>
<script setup>
import { defineProps,watch} from "vue";
const props = defineProps(["message"]);
//監(jiān)聽傳過來的數(shù)據(jù)
watch(()=>props.message,()=>{
console.log("傳遞過來的數(shù)據(jù)", props.message);
})
</script>
<style scoped></style>

總結(jié)
到此這篇關(guān)于vue中父組件通過props向子組件傳遞數(shù)據(jù)但子組件接收不到解決辦法的文章就介紹到這了,更多相關(guān)ue父組件向子組件傳遞數(shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue將時(shí)間戳轉(zhuǎn)換成自定義時(shí)間格式的方法
下面小編就為大家分享一篇vue將時(shí)間戳轉(zhuǎn)換成自定義時(shí)間格式的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-03-03
Vue filter格式化時(shí)間戳?xí)r間成標(biāo)準(zhǔn)日期格式的方法
今天小編就為大家分享一篇Vue filter格式化時(shí)間戳?xí)r間成標(biāo)準(zhǔn)日期格式的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-09-09
vue子元素綁定的事件, 阻止觸發(fā)父級(jí)上的事件處理方式
這篇文章主要介紹了vue子元素綁定的事件, 阻止觸發(fā)父級(jí)上的事件處理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11
el-input無法輸入的問題和表單驗(yàn)證失敗問題解決
在做項(xiàng)目的時(shí)候發(fā)現(xiàn)一個(gè)情況,輸入框無法輸入值并且表單校驗(yàn)失靈,所以下面這篇文章主要給大家介紹了關(guān)于el-input無法輸入的問題和表單驗(yàn)證失敗問題解決的相關(guān)資料,需要的朋友可以參考下2023-02-02

