问题说明
子组件监听父组件传过来的infoData,父组件的infoData是一个个添加属性的
父组件中infoData的添加对象代码如下:
this.infoData.customerId = data.customerId;
this.infoData.customerName = data.customerName;
this.infoData.customerAdress = data.customerAdress;
this.infoData.customerLevel = data.customerLevel;
this.infoData.customerStatus = data.customerStatus;
this.infoData.customerRemark = data.customerRemark;
子组件就监听了一次,而且打印存在问题:
watch: {
// 获取基本信息数据并赋值baseInfo数组
infoData: {
handler(newVal) {
console.log(newVal);//打印的对象有值
this.baseInfo.map(item => {
item.info = newVal[item.key];
console.log(newVal[item.key]);//打印的对象是undefined
return item;
})
},
deep: true,
immediate: true,
}
},
原因
watch使用deep属性可以深入监听对象的属性改变,但父组件中添加对象属性时是无法监听到的
解决方法
1、子组件中使用延迟setTimeout
watch: {
// 获取基本信息数据并赋值baseInfo
baseInfoData: {
handler(newVal) {
setTimeout(() => {
this.baseInfo.map(item => {
item.info = newVal[item.key];
return item;
}, 500)
})
},
deep: true,
immediate: true,
}
},
2、父组件中不要一个个添加属性,使用类来构造对象
customer.js中:
// 客户信息类
export class customer {
constructor(customerInfo) {
this.customerId = customerInfo.customerId;
this.customerName = customerInfo.customerName;
this.customerAddress = customerInfo.customerAdress;
this.customerLevel = customerInfo.customerLevel;
this.customerStatus = customerInfo.customerStatus;
this.customerRemark = customerInfo.customerRemark;
}
}
父组件中引入方法并构造
// 使用类构造客户详情对象,避免多次添加属性,无法被监听到
this.infoData = new customer(data);