一、前言
现象: 第一次打开网页,先点击修改,再点击新增,发现输入框竟然有值
原因: 点击修改后,关闭对话框的时候,置空失效了
分析: 主人公resetFields有问题
线索1: Dialog 的内容是懒渲染的,即在第一次被打开之前,传入的默认 slot不会被渲染到 DOM 上
线索2: vue数据改变(先执行同步所有)再去更新DOM(异步代码)
无问题操作: 第一次打开网页,先点击新增按钮 -> dialog出现 -> el-form组件第一次挂载(关联的addForm对象的属性的值为空字符串) el-form组件内绑定了初始值,所以后续调用resetFields的时候,它可以用到空字符串初始值来重置
有问题: 第一次打开网页,先点击修改按钮 -> 虽然dialog变量为true了但是同步代码把addForm对象里赋值了(默认值) -> DOM更新异步 -> dialog出现 -> el-form组件第一次挂载(使用addForm内置做回显然后第一次el-fonm内绑定了初始值(有值)) -> 以后做重置,它就用绑定的带值的做重置
二、现象
按照1、2、3的顺序操作出现 bug ,图片展示:
按照1、2、3的顺序,在第二步、 第三步 操作时出现的图片,(设计时,是要点击第三步的地方是提出的框的数据清空,按照上面的步骤操作出现如下的情况)
按照1、3、2、3的顺序出现如下情况(这是正确的情况,我们要解决上面那种情况)
三、代码
错误时:
/** 修改按钮操作 */
handleUpdate (row) {
this.reimId_row = row.reimId || this.ids //本行reimId
this.reset();
const reimId = row.reimId || this.ids
// 让el-dialog第一次挂载el-form时,先用addForm空字符串初始值绑定到内部,后续用作resetFields重置
// 所以让真实DOM先创建并在内部绑定好复制好初始值
// 接着我们真实DOM更新后绑定好了,咱们再给数据回显
// 注意:我们给v-model对象赋值只是影响当前显示的值,不会影响到resetFields复制的初始值
// 数据回显(回填)
getReim(reimId).then(response => {
console.log(response.data, 'response');
this.form = response.data;
this.isCar = this.form.digest.indexOf('汽车费用') !== -1;
this.isOther = this.form.digest.indexOf('其他') !== -1;
// 汽车费
this.carTableData = response.data.carFeeDetailList;
// 其他
this.otherTableData = response.data.otherFeeDetailList;
});
this.open = true;
this.title = "修改报销申请";
},
正确时:
/** 修改按钮操作 */
handleUpdate (row) {
this.reimId_row = row.reimId || this.ids //本行reimId
this.reset();
const reimId = row.reimId || this.ids
// $nextTick()回调推迟到下一个 DOM 更新周期之后执行
this.$nextTick(() => {
getReim(reimId).then(response => {
console.log(response.data, 'response');
this.form = response.data;
this.isCar = this.form.digest.indexOf('汽车费用') !== -1;
this.isOther = this.form.digest.indexOf('其他') !== -1;
// 汽车费
this.carTableData = response.data.carFeeDetailList;
// 其他
this.otherTableData = response.data.otherFeeDetailList;
});
})
this.open = true;
this.title = "修改报销申请";
},