vue2中watch监听数组变化,在push数组的时候,watch监听报错,不知道为什么?

watch监听

insuredpersons: {

  handler(newValue, oldValue) {
    // 当输入完18位身份证号之后调用获取保费接口
    for (let i = 0; i < newValue.length; i++) {
      console.log(oldValue[i].idNo, "oldValue[i].idNo");
      if (oldValue[i].idNo != newValue[i].idNo) {
        if (newValue[i].idNo.length == 18) {
          console.log("调用watch", newValue[i].age);
          this.getRiskBWYL();
        }
      }
      // 当社保标志变化之后调用获取保费接口
      if (
        oldValue[i].socialSecurityFlag != newValue[i].socialSecurityFlag
      ) {
        this.getRiskBWYL();
      }
    }
  },
  deep: true
},

计算属性
insuredpersons() {

  return JSON.parse(
    JSON.stringify(this.$store.state.insuredperson.insuredperson)
  );
},
insuredperson() {
  return this.$store.state.insuredperson.insuredperson;
},


添加数据
personadd() {

  let addconcat = {
    relationshipBbr: {
      id: "01",
      text: "本人"
    },
    relationshipTbr: {
      id: "01",
      text: "本人"
    },
    name: "",
    idNo: "",
    sex: "1",
    birthday: "",
    age: "",
    ageDay: "",
    phoneNo: "",
  };

  this.insuredperson.push(addconcat);


},

报错
image.png

阅读 2.1k
1 个回答

比如insuredpersons原本是3位,这是watch-insuredpersons中oldValue的长度,当你push一个数据后insuredpersons变成了4位,这是watch-insuredpersons中newValue的长度,所以你用newValue的长度去遍历oldValue,当遍历到第四位的时候,oldValue[3]是undefined,此时oldValue[3].idNo不就报错了吗

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题