Vue之没有字段造成双向绑定失效问题

一、场景

在一次使用ElementUI的时间选择器(el-time-picker)时,后端需要接受两个时间(startTime和endTime),但因为时间选择器是通过数组(times)绑定的,所以我们只能在提交的拆成两个值,然后查看详情时重新赋值times,但是在使用过程中却出现了这样的问题:创建的时候没有问题,查看的时候也没问题,但就是不能修改!!!???

二、问题根源

这种问题往往是由于双向绑定问题影响的,看一下我的代码:

handleUpdate(row) {
  this.reset();
  this.form = Object.assign({}, row);
  if (row.tankerFlag === '1' && row.startTime && row.endTime) {
    this.form.times = [new Date(row.startTime), new Date(row.endTime)];
  }
  this.open = true;
}

注意看,我们是先赋值的form,然后再通过判断赋值的时间,但是row中实际没有times字段,然后赋值时Vue将整个form来双向绑定,而实际上却没有times字段的绑定,所以造成了只能查看不能回传(双向绑定失效)的问题。

三、解决

下面提供三种解决方案

1. 赋值前添加字段

我们在赋值form时,给定times字段,如下:

handleUpdate(row) {
  this.reset();
  row.times = undefined;
  this.form = Object.assign({}, row);
  if (row.tankerFlag === '1' && row.startTime && row.endTime) {
    this.form.times = [new Date(row.startTime), new Date(row.endTime)];
  }
  this.open = true;
}

注意: 以上会修改原数据,可能造成元数据错误问题,我们可以先深拷贝,然后添加字段

handleUpdate(row) {
  this.reset();
  const form = Object.assign({}, row);
  form.times = undefined;
  this.form = form;
  if (row.tankerFlag === '1' && row.startTime && row.endTime) {
    this.form.times = [new Date(row.startTime), new Date(row.endTime)];
  }
  this.open = true;
}

2. 先赋值字段,后赋值form(推荐)

既然先赋值form有问题,那么干脆我们先赋值字段:

handleUpdate(row) {
  this.reset();
  const form = Object.assign({}, row);
  if (row.tankerFlag === '1' && row.startTime && row.endTime) {
    form.times = [new Date(row.startTime), new Date(row.endTime)];
  }
  this.form = form;
  this.open = true;
}

3. 使用Vue.set

其实Vue有一个内置的方法,用于添加双向绑定的字段:

handleUpdate(row) {
  this.reset();
  this.form = Object.assign({}, row);
  if (row.tankerFlag === '1' && row.startTime && row.endTime) {
    this.$set(this.form, 'times', [new Date(row.startTime), new Date(row.endTime)]);
  }
  this.open = true;
}

四、总结

造成这样的问题其实其实是由于代码规范的问题,如果使用typeScript就没有这种问题。明明没有相应的字段,却要赋值,这也是弱语言的一个问题吧。一般的js逻辑可能没有太大问题,但是在双向绑定面前,还是要尽可能的规范一些。所以我们还是比较推荐第一和第二种解决方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

会功夫的李白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值