使用props傳值時無法在mounted處理的解決方案
props傳值無法在mounted處理的解決
遇到的問題
父組件傳值,在子組件中不能用mounted處理
export default{ ?? ?props:['floor1'], ?? ?data(){ ?? ??? ?return { ?? ??? ??? ?floor1_0:'', ?? ??? ??? ?floor1_1:'', ?? ??? ??? ?floor1_2:'', ?? ??? ?} ?? ?}, ?? ?mounted(){ ?? ??? ?console.log(this.floor1) ? ? ? ? ? ? //打印出的不是所傳的值 ?? ??? ?this.floor1_0 = this.floor1[0]; ? ? ? ?? ?} }
因為props為異步傳值(就是在父組件沒有加載完數(shù)據(jù)時,floor1就傳遞到了子組件,此時floor1還沒被附上值,先執(zhí)行了子組件的mounted),而mounted執(zhí)行一次后無法改變floor1的值。
解決
使用偵聽器watch,當(dāng)floor1改變時,重新計算
watch:{ ?? ?floor1:function(val){ ?? ??? ?this.floor1_0 = val[0]; ?? ??? ?this.floor1_1 = val[1]; ?? ?} }
vue筆記(props和mounted)
1.mounted
1.1mounted中使用$nextTick會導(dǎo)致頁面掛掉
mounted() { // 頁面卡死 ? ? this.$nextTick(() => { ? ? ? this.setUrl() ? ? }) ? }
2.props
2.1props傳過去的值,第一時間在mounted是獲取不到的。因為是異步傳值的。
解決方法:
(1)使用watch
(2)將需要進行的處理在父組件進行操作,然后將操作完的值直接傳給子組件。
watch: { ? ?datas: function (val) { ? ? ?? ? ? } ? } 或 (父) ?<examAchSearchHeader :exprotUrl="exprotUrl"></examAchSearchHeader> ?... this.exportUrl = XXXX (子) props: { ? ? exportUrl: String }
2.2通過props傳給子組件的值變化后子組件接收到 和 通過refs訪問子組件方法中使用接收到的參數(shù)變化的順序問題
通過refs訪問時,接收到的參數(shù)是變化前的參數(shù)。還是因為異步的問題。可以強制賦值改變,或用watch等。
?// parent ?<examAchTable ref="achTable" :dataList="examAchList"></examAchTable> ? ?// 若這里不強制賦值一下,在examAchList變化后直接調(diào)用子組件的transData方法時,子組件dataList仍是變化前的值 ?this.$refs.achTable.dataList = this.examAchList ?this.$refs.achTable.transData(res.data.totalRecord) ? ?// child ?transData(total) { ? ? ? if (this.dataList)? ? ? // ... }
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
koa2+vue實現(xiàn)登陸及登錄狀態(tài)判斷
這篇文章主要介紹了koa2+vue實現(xiàn)登陸及登錄狀態(tài)判斷,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值 ,需要的朋友可以參考下2019-08-08vue中g(shù)et請求如何傳遞數(shù)組參數(shù)的方法示例
這篇文章主要介紹了vue中g(shù)et請求如何傳遞數(shù)組參數(shù)的方法示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11