el-form组件使用resetFields重置失效问题解决,有效避坑
1. 问题
用el-form写了包含三个字段的表单,使用resetFields方法进行重置,发现点击重置或要清空校验时是失效的。
代码:
<template>
<div>
<el-form :inline="true" size="mini" style="float: right" :model="queryParams.args" ref="queryForm">
<el-form-item label="姓名">
<el-input
style="width:160px"
size="mini"
placeholder=""
v-model.trim="queryParams.args.name"
clearable
></el-input>
</el-form-item>
<el-form-item label="账号">
<el-input
style="width:160px"
size="mini"
placeholder=""
v-model.trim="queryParams.args.no"
clearable
></el-input>
</el-form-item>
<el-form-item label="性别">
<el-select v-model="queryParams.args.sex" placeholder="请选择" clearable>
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</el-form-item>
<el-form-item>
<el-button type="primary" @click.native="search" size="mini">查询</el-button>
<el-button type="primary" @click.native="addUseroperator" size="mini">新增</el-button>
<el-button type="success" @click.native="reset" size="mini">重置</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
data() {
return {
queryParams: {
args:{
name: "",
no: "",
sex: null
}
},
options: [
{value: 0, label: '女'},
{value: 1, label: '男'}
]
}
},
methods: {
reset(){
this.$refs["queryForm"].resetFields()
},
}
}
</script>
点击重置按钮后,仍不能清空重置该表单:
刚开始以为是异步问题,在重置方法代码上加上方法this.$nextTick(()=>{}):
methods: {
reset(){
this.$nextTick(()=>{
this.$refs["queryForm"].resetFields()
})
},
}
测试后仍然没有效果,只能下一步解决:
2. 解决
仔细检查代码后,可以发现el-form-item没有添加prop属性,导致识别不到相应的字段属性,注意这里有个坑:就是el-form这里要加上“:model”字段,我这里是加“:model=“queryParams.args”,如果不加,resetFields也会同样失效。加上后的代码如下:
<template>
<div>
<el-form :inline="true" size="mini" style="float: right" :model="queryParams.args" ref="queryForm">
<el-form-item label="姓名" prop="name">
<el-input
style="width:160px"
size="mini"
placeholder=""
v-model.trim="queryParams.args.name"
clearable
></el-input>
</el-form-item>
<el-form-item label="账号" prop="no">
<el-input
style="width:160px"
size="mini"
placeholder=""
v-model.trim="queryParams.args.no"
clearable
></el-input>
</el-form-item>
<el-form-item label="性别" prop="sex">
<el-select v-model="queryParams.args.sex" placeholder="请选择" clearable>
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</el-form-item>
<el-form-item>
<el-button type="primary" @click.native="search" size="mini">查询</el-button>
<el-button type="primary" @click.native="addUseroperator" size="mini">新增</el-button>
<el-button type="success" @click.native="reset" size="mini">重置</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
data() {
return {
queryParams: {
args:{
name: "",
no: "",
sex: null
}
},
options: [
{value: 0, label: '女'},
{value: 1, label: '男'}
]
}
},
methods: {
reset(){
this.$refs["queryForm"].resetFields()
},
}
}
</script>
点击重置按钮测试后,确实有效了,问题解决。