如何在vee-validate中为input输入框实现条件样式设置
实现方案
你可以通过以下两种方式实现校验状态的样式绑定,适配你当前的代码写法:
方案1:使用v-field作用域插槽(适配所有API风格,无需额外引入API)
把你原有v-field的自闭合写法改为插槽写法,插槽会直接暴露当前字段的所有校验状态,直接用状态绑定class即可:
<div id="app"> <v-form @submit="onSubmit"> <!-- 修改为插槽写法 --> <v-field name="email" :rules="validateEmail" v-slot="{ field, error, valid, touched }"> <input v-bind="field" class="TextInput" :class="{ 'has-error': touched && error, // 已交互且校验不通过时加错误类 'success': touched && valid // 已交互且校验通过时加成功类 }" > </v-field> <error-message name="email"></error-message> ... <button >Sign up</button> </v-form> </div>
如果你不需要「用户交互后才显示样式」的逻辑,直接删除
touched &&判断即可,改成'has-error': error, 'success': valid。
方案2:使用useFieldState获取字段状态(适合组合式API场景)
如果你用的是Vue3组合式API,可以直接在逻辑层获取对应字段的校验状态,不需要修改原有的v-field写法:
- 逻辑层引入API获取状态:
import { useFieldState } from 'vee-validate' // 传入字段名获取对应校验状态 const { error, valid, touched } = useFieldState('email')
- 模板直接绑定class即可:
<v-field name="email" as="input" :rules="validateEmail" class="TextInput" :class="{ 'has-error': touched && error, 'success': touched && valid }" ></v-field>
内容的提问来源于stack exchange,提问作者Li Xiu Ying
相关产品推荐
相关产品推荐

