You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何重置Vuelidate指定字段使$error标记为false?

解决Vuelidate $reset()后普通输入框$error仍为true的问题

这个问题的核心是事件绑定方式错误,导致$touch()被意外触发,使得重置后的验证状态又被标记为dirty,最终让$error保持为true。

问题原因分析

你在普通输入框里用了:oninput和:onblur这种属性绑定语法,而非Vue标准的事件绑定语法@input和@blur。:oninput="$v.form.firstName.$touch()"会在组件渲染时立即执行一次$touch(),直接把验证状态设为$dirty: true;后续即便调用$reset()重置状态,也可能因为渲染机制或意外的交互触发,让$touch()再次执行,导致$error(等于$dirty && $invalid)无法变为false。

而Vuetify组件内部已经正确处理了事件绑定与验证状态的交互逻辑,所以它的$error能正常被重置。

修改方案

把输入框的:oninput和:onblur替换为Vue的事件绑定语法@input和@blur,这样只有当用户实际输入或失焦时才会触发$touch()。调用$reset()时,就能正确将$dirty设为false,$error自然会变成false(因为$error = $dirty && $invalid,$dirty为false时结果必然为false)。

修改后的完整代码

<html>
<head>
<script src="https://unpkg.com/vuelidate@0.6.1/dist/validators.min.js"></script>
<script src="https://unpkg.com/vuelidate@0.6.1/dist/vuelidate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<style>
input.raw { border: solid; }
.is-invalid { border-color: #FF5252 !important; }
</style>
</head>
<body>
<div id="app">
<label for="firstName">First Name</label>
<!-- 替换事件绑定语法 -->
<input v-model="form.firstName" id="firstName" class="raw" :class="{ 'is-invalid': $v.form.firstName.$error }" type="text" width="100%" @input="$v.form.firstName.$touch()" @blur="$v.form.firstName.$touch()" />
<button @click="$v.form.firstName.$touch()"> $touch </button>
<button @click="$v.form.firstName.$reset()"> $reset </button>
<pre>{{ $v.form.firstName }}</pre>
</div>

<script>
Vue.use(window.vuelidate.default)
var validationMixin = window.vuelidate.validationMixin
const { maxLength, required } = window.validators
new Vue({
  el: '#app',
  mixins: [validationMixin],
  data: () => ({ form: { firstName: '', lastName: '' } }),
  validations: {
    form: {
      firstName: { required, maxLength: maxLength(2) },
      lastName: { required, maxLength: maxLength(2) },
    }
  }
})
</script>
</body>
</html>

验证效果

修改后点击$reset按钮:

  • $dirty会被重置为false
  • $error因$dirty为false,结果变为false
  • 输入框的is-invalid类会自动移除,红色边框消失

内容的提问来源于stack exchange,提问作者bdoubleu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 13:02:43