問題描述
父組件給子組件傳對象,子組件用這個對象中的字段填充模板,子組件定義 info 為 {},會報 TypeError: Cannot read properties of undefined (reading 'refundText')的錯誤,但頁面上會正確顯示數據。
原因
推測這個錯誤發生在子組件的 created() 與 mounted() 生命周期中,因為這個時候子組件還沒有接受到父組件的 props 傳過來的值。
解決
- 子組件定義 info 時,為模板中用到的所有屬性定義一個空值,如:
info: {
refundText: ''
}
- 在子組件data中掛載一個屬性,用來接收父組件傳過來的值,在watch監聽中賦值並進行操作,為了發現對象內部值的變化,可以在選項參數中指定 deep: true,監聽數組的變動不需要這么做。
<div>
<span>{{ data.name }}</span>
</div>
export default {
name: 'ChildPack',
//也可以指定默認類型和默認值
props: {
fartherMsg: {
type: Object,
}
},
data(){
data:{}
},
created() {
console.log(this.fartherMsg.testMsg) // error
},
mounted(){
console.log(this.fartherMsg) // {}
},
updated(){
console.log(this.fartherMsg.testMsg) //{code:01,name:'test'}
},
watch:{
fartherMsg:{
handler(newVal,oldVal){
this.data = this.fartherMsg.testMsg
},
deesp:true
}
}
----2021.10.11
參考: