Vue 父組件給子組件傳對象,子組件中報錯 Cannot read properties of undefined


問題描述

父組件給子組件傳對象,子組件用這個對象中的字段填充模板,子組件定義 info 為 {},會報 TypeError: Cannot read properties of undefined (reading 'refundText')的錯誤,但頁面上會正確顯示數據。

原因

推測這個錯誤發生在子組件的 created() 與 mounted() 生命周期中,因為這個時候子組件還沒有接受到父組件的 props 傳過來的值。

解決

  1. 子組件定義 info 時,為模板中用到的所有屬性定義一個空值,如:
 info: {
    refundText: ''
}
  1. 在子組件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

參考:

  1. vue2.x組件間傳值及在vue子組件中操作父組件數據時生命周期的問題


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM