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.
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");
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
