Vue3之父子組件異步props數(shù)據(jù)的傳值方式
Vue3父子組件異步props數(shù)據(jù)的傳值
在寫前端頁面時碰到一個問題,就是點擊編輯按鈕傳遞這一行信息給子組件編輯頁,展示該條數(shù)據(jù)詳細數(shù)據(jù);
但還沒有點擊編輯按鈕,其實編輯頁已經(jīng)初始化了,是因為在父組件中已經(jīng)導入使用了該編輯頁;
例如:在 Editor.vue中有這樣代碼:
let prop = defineProps(["dataInfo"]) console.log(prop.dataInfo);
進入首頁時控制臺已經(jīng)運行了這段代碼console.log(prop.dataInfo) 并且為空對象;
但是子組件并沒有接收到父組件的數(shù)據(jù);
原因
是因為如果父組件的props值是通過異步操作獲取的,那么在最初渲染子組件時,props可能還沒有被賦值。而我正是使用異步操作把值通過props傳給子組件的;
代碼如下:
在父組件一個函數(shù)中給dataInfo賦值:
// 子組件標簽 <Editor :dataInfo="dataInfo" ref="EditorRef" @refresh="funFindItemInfo" /> let EditorRef = ref() let dataInfo = ref({}) //傳遞給編輯頁的數(shù)據(jù) //編輯按鈕 function handlEditor(row) { dataInfo.value = row; // 信息傳遞到組件 EditorRef.value.openEditor() //打開對話框 }
解決方案
這種情況下,可以使用watchEffect
或watch
來監(jiān)聽props的變化,確保當props值變化時能作出相應的處理。
小結(jié):Vue 3中props的值在組件實例創(chuàng)建初期就被初始化并傳遞給子組件,并且在組件的整個生命周期內(nèi),只要父組件的props數(shù)據(jù)發(fā)生變化,就會觸發(fā)子組件的相應更新。
總代碼如下:
- 父組件:
// 子組件標簽 <Editor :dataInfo="dataInfo" ref="EditorRef" @refresh="funFindItemInfo" /> let EditorRef = ref() let dataInfo = ref({}) //傳遞給編輯頁的數(shù)據(jù) //編輯按鈕 function handlEditor(row) { dataInfo.value = row; // 信息傳遞到組件 EditorRef.value.openEditor() //打開對話框 }
- 子組件:
// 標簽: <el-form-item label="ID"> <el-input v-model="ItemFormData.id" disabled></el-input> </el-form-item> <el-form-item label="名字"> <el-input v-model="ItemFormData.name"></el-input> </el-form-item> ........ let prop = defineProps(["dataInfo"]) const emit = defineEmits(["refresh"]) let isDialog = ref(false) // 是否拉開抽屜 let ItemFormData = ref({}) // 數(shù)據(jù)對象 defineExpose({ // 對外暴露控制拉開抽屜的方法 openEditor() { isDialog.value = true }, }); watch(()=>prop.dataInfo,(newVal,oldVal)=>{ console.log("新值:",newVal); console.log("舊值:",oldVal); let {id,name,price,detail,pic,address,createtime} = prop.dataInfo //解構(gòu) 切斷響應 ItemFormData.value = {id,name,price,detail,pic,address,createtime} console.log("dada", ItemFormData.value); })
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue2.x,vue3.x使用provide/inject注入的區(qū)別說明
這篇文章主要介紹了vue2.x,vue3.x使用provide/inject注入的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04vue路由對不同界面進行傳參及跳轉(zhuǎn)的總結(jié)
這篇文章主要介紹了vue路由對不同界面進行傳參及跳轉(zhuǎn)的總結(jié),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-04-04詳解Vue3 Composition API中的提取和重用邏輯
這篇文章主要介紹了Vue3 Composition API中的提取和重用邏輯,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-04-04