vue中父組件通過props向子組件傳遞數(shù)據(jù)但子組件接收不到解決辦法
問題:
父組件在掛載時向后端發(fā)起請求獲取數(shù)據(jù),然后將獲取到的數(shù)據(jù)傳遞給子組件,子組件想要在掛載時獲取數(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(() => {
//模擬異步請求
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,所以獲取不到異步請求后獲取到的數(shù)據(jù)
解決方法
方法一:使用v-if控制子組件渲染的時機(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(() => {
//模擬異步請求
setTimeout(() => {
message.value = "1312";
isShow.value=true;//獲取數(shù)據(jù)成功,再讓子組件渲染
}, 0);
});
</script>
<style scoped></style>
方法二:使用watch對父組件傳遞過來的數(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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue3+vueuse實(shí)現(xiàn)放大鏡示例詳解
這篇文章主要為大家介紹了Vue3+vueuse實(shí)現(xiàn)放大鏡示例過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
VUE項(xiàng)目啟動沒有問題但代碼中script標(biāo)簽有藍(lán)色波浪線標(biāo)注
這篇文章主要給大家介紹了關(guān)于VUE項(xiàng)目啟動沒有問題但代碼中script標(biāo)簽有藍(lán)色波浪線標(biāo)注的相關(guān)資料,文中將遇到的問題以及解決的方法介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05
vue如何使用swiper插件修改左右箭頭的默認(rèn)樣式
這篇文章主要介紹了vue如何使用swiper插件修改左右箭頭的默認(rèn)樣式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01
vue.js框架實(shí)現(xiàn)表單排序和分頁效果
這篇文章主要為大家詳細(xì)介紹了vue.js框架實(shí)現(xiàn)表單排序和分頁效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-08-08
Elementui如何限制el-input框輸入小數(shù)點(diǎn)
這篇文章主要介紹了Elementui如何限制el-input框輸入小數(shù)點(diǎn),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08
淺談Vue數(shù)據(jù)響應(yīng)思路之?dāng)?shù)組
這篇文章主要介紹了淺談Vue數(shù)據(jù)響應(yīng)思路之?dāng)?shù)組,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11

