watch的deep属性监听对象,没有监听到对象的属性新增

1 篇文章 0 订阅

问题说明

子组件监听父组件传过来的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);
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值