清除表单校验
最近项目中遇到一个问题,框架用的vue,ui组件使用的是antd,登录界面有账户密码登录、验证码登录还有注册忘记密码啥的,总归就是四个表单之间的切换,上图看。
现在有个啥问题呢,点击“注册账户”并且点击第一个输入框后什么也不输,然后就点别处一下触发了表单验证,也就是这样的⬇️
然后点击“已有账号,去登录”,造成下面的局面
校验还在,并且带到了登录页。
试了一个办法:
this.$nextTick(()=>{this.$refs['form3'].resetFields()})
然而不好使!
后来发现给表单加key就好了
:key="+new Date()"
vue在渲染元素的时候会复用现有元素,而不是每次都重新渲染页面,加上key属性,如果key变化则重新渲染页面(key注意要唯一),时间是变化的,这样每次切换表单的时候key的值发生变化之后页面重新渲染,表单重新渲染,验证信息就被清空了。
代码如下:
<a-form-model :form="form2" :model="form2" :rules="rules2" ref="form2" :key="+new Date()">
<a-alert
type="error"
:closable="true"
v-show="error"
:message="error"
showIcon
style="margin-bottom: 24px"
/>
<a-form-model-item prop="mobile">
<a-input
autocomplete="autocomplete"
size="large"
v-model="form2.mobile"
placeholder="请输入手机号"
v-placeholder
>
<a-icon slot="prefix" type="phone" />
</a-input>
</a-form-model-item>
<a-form-model-item>
<a-row :gutter="8" style="margin: 0 -4px">
<a-col :span="16">
<a-input
size="large"
placeholder="请输入验证码"
v-model="form2.code"
v-placeholder
>
<a-icon slot="prefix" type="mail" />
</a-input>
</a-col>
<a-col :span="8" style="padding-left: 4px">
<a-button
style="width: 100%"
class="captcha-button"
size="large"
@click="getCode(1)"
v-if="!isCountDown"
>获取验证码</a-button
>
<a-button
style="width: 100%"
class="captcha-button"
size="large"
v-else
:disabled="isCountDown"
>{{ second }}s后获取</a-button
>
</a-col>
</a-row>
</a-form-model-item>
<a-form-model-item prop="password">
<a-input-password
size="large"
placeholder="设置登录密码(6-20位字母数字组合)"
autocomplete="autocomplete"
type="password"
v-model="form2.password"
v-placeholder
>
<a-icon slot="prefix" type="lock" />
</a-input-password>
</a-form-model-item>
<a-form-model-item prop="confirmPwd">
<a-input-password
size="large"
placeholder="再次输入登录密码"
autocomplete="autocomplete"
type="password"
v-model="form2.confirmPwd"
v-placeholder
>
<a-icon slot="prefix" type="lock" />
</a-input-password>
</a-form-model-item>
<div>
<a-checkbox v-model="checkedItems"
>您已阅读并同意<a
href="#"
target="_blank"
>《隐私协议》</a
></a-checkbox
>
</div>
<a-form-model-item>
<a-button
:loading="logging"
style="width: 100%; margin-top: 24px"
size="large"
htmlType="submit"
type="primary"
@click="onSubmitRegister"
:disabled="!checkedItems"
>注册</a-button
>
</a-form-model-item>
<div>
<a
href="javascript:void(0);"
style="float: right"
@click.stop="changeForm(1)"
>已有账号,去登录</a
>
</div>
</a-form-model>