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>
打印結果: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控制子組件渲染的時機
//父組件 <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ù)進行監(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>
總結
到此這篇關于vue中父組件通過props向子組件傳遞數(shù)據(jù)但子組件接收不到解決辦法的文章就介紹到這了,更多相關ue父組件向子組件傳遞數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
VUE項目啟動沒有問題但代碼中script標簽有藍色波浪線標注
這篇文章主要給大家介紹了關于VUE項目啟動沒有問題但代碼中script標簽有藍色波浪線標注的相關資料,文中將遇到的問題以及解決的方法介紹的非常詳細,需要的朋友可以參考下2023-05-05Elementui如何限制el-input框輸入小數(shù)點
這篇文章主要介紹了Elementui如何限制el-input框輸入小數(shù)點,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08