How to Reset el-form in Element UI and Extract the Reset Logic as a Global Method

This guide explains how to add a ref to an Element UI el-form, use resetFields() to clear form inputs on reset or cancel actions, and then abstract the reset logic into a reusable global Vue method for use across multiple pages.

The Dominant Programmer
The Dominant Programmer
The Dominant Programmer
How to Reset el-form in Element UI and Extract the Reset Logic as a Global Method

Scenario

When using el-form in Element UI, clicking a reset or cancel button should clear the form fields.

Implementing Reset

Add a ref to the form

<el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">

In the reset button handler call the form’s resetFields() method: this.$refs["queryForm"].resetFields(); The prop attribute must be set on each el-form-item that needs to be reset, e.g.:

<el-form-item label="Employee Name" prop="xm">
  <el-input v-model="queryParams.xm" placeholder="Enter employee name" clearable size="small" @keyup.enter.native="handleQuery"></el-input>
</el-form-item>

For cancel actions on add/edit dialogs, reset the bound model to undefined before calling resetFields():

reset() {
  this.form = {
    id: undefined,
    bcbh: undefined,
  };
  this.$refs["form"].resetFields();
}

Extracting the Reset Logic as a Global Method

In main.js attach the helper to Vue: Vue.prototype.resetForm = resetForm; Import the function from a utility file: import { resetForm } from "@/utils/badao"; The utility defines:

export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields();
  }
}

Components can now invoke the global method:

resetQuery() {
  this.resetForm("queryForm");
},
reset() {
  this.form = { id: undefined, bcbh: undefined };
  this.resetForm("queryForm");
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Vue.jsElement UIel-formform resetglobal method
The Dominant Programmer
Written by

The Dominant Programmer

Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.