[Reprint] Solve the problem that the Element resetFields() reset form does not take effect

Preface

Since the element-ui framework was used in the background of the company, there was a problem that the resetFields form could not be reset during the development process. Recording the solution here can also help future students to step on the pit.

1. Reproduce the problem

Because the "Add" and "Edit" fields are the same, I put them in a pop-up form, which also saves code resource overhead. If you write the pop-ups separately, this problem won't occur.

重现步骤:进入列表页后,先打开编辑框,然后打开新增框,新增框会填充第一次打开的编辑框内容

Open the edit box first
edit

Then open the new box, the
Add
new edit box is also filled with data

form的@closed 方法调用了resetFields,但没有生效
resetForm() {
  this.$refs['form'].resetFields();
},

2. Reasons why resetFields() does not take effect

1. This method is used to set the data of the form form to the initial value
2. This initial value is assigned during the life cycle of the form mounted
3. So, before the form mounted, if the form form is assigned, then call resetFields() is invalid, because the initial value of the form has been assigned before mounted

3. Solution

As long as the assignment operation is performed after the form is mounted, the problem can be solved perfectly, that is, use the "this.$nextTick" method when clicking edit assignment. Code!
The method of opening the pop-up window before modification:

onShow(type, row) {
  this.visible = true;
  if (type === 'create') {
    this.dialogTitle = '添加XX';
  } else if (type === 'update') {
    this.dialogTitle = '编辑XX';
    this.form.name = row.name;
    this.form.des = row.des;
  }
},

The modified method of opening the pop-up window:

onShow(type, row) {
  this.visible = true;
  if (type === 'create') {
    this.dialogTitle = '添加XX';
  } else if (type === 'update') {
    this.dialogTitle = '编辑XX';
    this.$nextTick(() => { // 注意看这里
      this.form.name = row.name;
      this.form.des = row.des;
    });
  }
},

After this, this.$refs['form'].resetFields();it takes effect

Original address: http://raboninco.com/VzoV

Guess you like

Origin blog.csdn.net/z00001993/article/details/105979810