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,监听数组的变动不需要这么做。
{{ data.name }}
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子组件中操作父组件数据时生命周期的问题