使用dialog+form组件时,form大多都会有重置需求,但点击重置按钮,有的时候resetFields方法就仿佛失效一样。
本文以登录弹框为例,解决resetFields方法失效问题
需求:当点击登录按钮时,登录表单弹出,当点击登录表单右上角的×时销毁表单,并清空表单
<el-button plain @click="centerDialogVisible = true" class="login">
登录/注册
</el-button>
<el-dialog
v-model="centerDialogVisible"
title="登录"
width="500"
destroy-on-close
center
@close="resetForm"
>
<el-form
ref="ruleFormRef"
style="max-width: 600px"
:model="ruleForm"
:rules="rules"
class="demo-ruleForm login-form"
status-icon>
<el-form-item prop="username">
<el-input :prefix-icon="User" v-model="ruleForm.username" class="user-form" placeholder="请输入用户名" ></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input type="password" :prefix-icon="Lock" v-model="ruleForm.password" class="password-form"placeholder="请输入密码" show-password></el-input>
</el-form-item>
<el-form-item>
<el-button class="login_btn" type="primary" size="default">登录</el-button>
</el-form-item>
</el-form>
</el-dialog>
效果如下
清空表单核心三步:
1、绑定 @close="resetForm"事件
<el-dialog
v-model="centerDialogVisible"
title="登录"
width="500"
destroy-on-close
center
@close="resetForm"
>
const resetForm = () => {
console.log(ruleFormRef.value,'sdaffa');
if (ruleFormRef.value) {
ruleFormRef.value.resetFields()
}
};
2、el-form标签定义 ref=“ruleFormRef”
<el-form
ref="ruleFormRef"
style="max-width: 600px"
:model="ruleForm"
:rules="rules"
class="demo-ruleForm login-form"
status-icon>
const ruleFormRef = ref<FormInstance>()
3、最关键一步(许多人就是因为这一步,无效果) el-form-item prop=“username”
<el-form-item prop="username">
<el-input :prefix-icon="User" v-model="ruleForm.username" class="user-form" placeholder="请输入用户名" ></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input type="password" :prefix-icon="Lock" v-model="ruleForm.password" class="password-form"placeholder="请输入密码" show-password></el-input>
</el-form-item>
const ruleForm = reactive({
username: '',
password:''
})
完成以上resetFields就可以实现清空表单的效果了
强调:
1、form组件上必须要有ref
2、form-item上必须要有prop属性