场景:
新增和编辑使用同一个对话框中的form组件
如果进入页面先进行编辑,form组件里表单的初始值就是所编辑对象的属性值
原因:
进入页面时对话框是没被挂载的,这时点击编辑后由于先给form绑定的数据对象赋值,再创建form,所以导致form的初始值是所编辑对像的值。
解决方案:
点击编辑时在渲染好对话款之后再给表单赋值
换而言之,给表单赋值加个延时即可
example
this.addDialogVisible = true; // 渲染表格
this.isEdit = true;
this.editUserId = row.id;
setTimeout(() => { // 加延时
this.addForm.username = row.username;
this.addForm.email = row.email;
this.addForm.mobile = row.mobile;
}, 10);
如果是根据id取值,赋值,则将表格渲染放在请求之后即可
this.addDialogVisible = true; // 渲染表格
this.isEdit = true;
this.editUserId = row.id;
const res = await this.$axios.get("users/" + row.id); // 因为请求是异步的,所以不用加延时
if (res.meta.status !== 200) return this.$msg.error(res.meta.msg);
this.addForm.username = res.data.username;
this.addForm.email = res.data.email;
this.addForm.mobile = res.data.mobile;