Vue、element-ui的resetFields()方法重置表单无效问题及解决办法
问题:使用this.$ref[‘form‘] .resetFields()无法重置表单项
原因:
1.没有给表单添加ref属性
<el-form ref="form"></el-form>
2.表单项el-form-item没有添加prop属性,prop属性需要与input框绑定的属性一致<el-form ref="form" :model="sizeForm" label-width="80px" size="mini">
<el-form-item label="活动名称" prop="name">
<el-input v-model="sizeForm.name"></el-input>
</el-form-item>
</el-form>
3.还有一个经常出现这种问题的场景是,当使用vuex的时候,新建表单与编辑表单复用,此时上述属性跟方法都添加了也无法达到清除表单的效果。此时我们再重新看一下element-ui的官方文档data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAhYAAABjCAYAAADHN0mIAAAZDUlEQVR4Ae1ca3LbSq/M4rQd7cWlhZz8v3cJKS8j2YWLX8FWk602MDPUwzapThULb8wIbA4Qyvavyf9cAVfAFXAFXAFXwBW4UwV+3SmP07gCroAr4Aq4Aq6AKzB5sDAIXAFXwBVwBVwBV+BuFfBgcbdSOpEr4Aq4Aq6AK+AKfBosXl9fJ1+ugTFgDBgDxoAxYAyMYEBHqXSweHt7m3xtrwYBAN+37d033zPfM2PAGNgqBqLv6D8PFjsaojxY+HDa6uHkfRu7xsA2MeDBYkdDRPYQerDY5oOZ3UvrfC+NAWNgCxjwYOHBwl+V7BwDWziIvEc3TGNgPxjwYLHzpuI3Fvt5WH3w+l4aA8bAFjDgwcKDhd9Y7BwDWziIvEc3TGNgPxjwYLHzpuI3Fvt5WH3w+l4aA8bAFjDgwcKDhd9Y7BwDWziIvEc3TGNgPxi442DxOp0Oh+lwOE2vNx3Ua/Os9d/PzRt5EPM3FlozlaNGma5VO/gHBvS6FROtdW0bwYF9jBNjwBj4KgzccbCIm4bm0mskLb+WLQPGWv8sx351+WCR3Suto8ockw0OLf8eHvZb/696kL2OMWQMGAM/BQNXDhZoItpgejI3GORgHTcv1WegQY7WuiN5stz70F03WKCuWjvVs8w8apfpYDP9KYeA92EsGgPGwD0xcOVgoTfh1gaC+GpA0AYX6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GLgFAx4sPFiUP2dxC7Ac64PJGDAGjIHnxIAHCw8WHix2jgEf7s95uPu++75/FwY8WOy8qcQN/i5weV0fbMaAMWAMPB8GPFh4sPDgsXMM+GB/voPd99z3/Dsx4MFi503Fbyx8wHznAeO1jT9j4Pkw4MHCg4XfWOwcAz7Yn+9g9z33Pf9ODAwPFuHoyzUwBowBY8AYMAaMgR4GJvn3S2SLroAr4Aq4Aq6AK+AKXF0BDxZXl86BroAr4Aq4Aq6AK6AV8GChFbHsCrgCroAr4Aq4AldXwIPF1aVzoCvgCrgCroAr4ApoBf4HXo53a3ikRGQAAAAASUVORK5CYII=
重点:resetField()方法不是将表单重置为空,而是重置为初始值所以当我们打开新建表单的时候,表单项绑定的属性值为空,在提交表单后,表单项绑定的值不为空,此时再打开新建表单是会有上一次的值出现,此时resetField()方法是无法清空表单的,因为在这次操作的时候,属性初始值就不为空。解决方法:
在提交表单成功后对绑定的值进行方法重置// 重置表单项属性
resetForm () {
return {
remark: ‘‘,
name: ‘‘
}
}
// 提交表单成功后重新给属性赋值
submit () {
//......调用成功
let self = this
let query = self.resetForm()
self.updateForm({ //此方法是自定义的vuex的action方法,大家可根据实际应用场景定义重置表单方法
form: query
)
}
self.$ref[‘form‘].resetFields() // 此时再调用resetFields()方法是为了清除表单验证而出现的错误
}
在对属性进行重置后执行resetFields方法,是因为对属性重置为空时,可能会触发表单规则的验证,此时执行resetFields会移除校验结果
————————————————
作者:CSDN博主「只想做个好人啊」
原文链接:https://blog.csdn.net/haidong55/article/details/90484138
页:
[1]