Vue开发中如何仅为空输入框单独添加错误样式类?
问题原因
你现在所有输入框都绑定了同一个全局hasError变量,只要校验触发失败,该变量设为true,所有输入框都会被添加上错误样式,这就是所有框都变红的原因。
修改步骤
1. 修改data定义,替换全局hasError为错误存储对象
把原来的hasError: false改成errors: {},用来存储每个字段的错误状态
data: () => { return { // 删掉原来的hasError: false errors: {}, // 新增错误存储对象 note: { title: '', content: '', applies_to_date: '', status_id: null, note_type: '', }, // 其他原有数据保持不变 } }
2. 修改校验逻辑checkInputs,按字段判断空值
checkInputs() { // 每次校验先清空之前的错误记录 this.errors = {} // 逐个判断必填字段是否为空,你可以按需调整要校验的字段范围 if (!this.note.title.trim()) { this.errors.title = true } if (!this.note.content.trim()) { this.errors.content = true } // 如果需要其他字段必填也可以在此处添加规则,例如: // if (!this.note.applies_to_date) this.errors.applies_to_date = true // if (!this.note.status_id) this.errors.status_id = true // if (!this.note.note_type.trim()) this.errors.note_type = true // 判断是否存在错误 if (Object.keys(this.errors).length > 0) { Swal.fire( 'Błąd', 'Proszę wypełnić wszystkie pola oznaczone gwiazdką!', 'error' ) return true } return false }
3. 修改模板中每个输入框的类绑定逻辑
每个字段单独判断自身是否存在错误:
<!-- Title字段 --> <CInput label="Title 123" type="text" id="title" placeholder="Title" v-model="note.title" :class="{ 'text-danger invalid': errors.title }"></CInput> <!-- Content字段 --> <CInput textarea="true" label="Content" id="content" :rows="9" placeholder="Content.." v-model="note.content" :class="{ 'text-danger invalid': errors.content }"></CInput> <!-- 日期字段 --> <CInput label="Applies to date" type="date" id="applies_to_date" v-model="note.applies_to_date" :class="{ 'text-danger invalid': errors.applies_to_date }"></CInput> <!-- 状态选择字段 --> <CSelect id="status_id" label="Status" :value.sync="note.status_id" :plain="true" :options="statuses" :class="{ 'text-danger invalid': errors.status_id }" > </CSelect> <!-- 笔记类型字段 --> <CInput label="Note type" type="text" id="note_type" v-model="note.note_type" :class="{ 'text-danger invalid': errors.note_type }"></CInput>
4. 修复样式选择器问题(可选但建议)
你当前的样式会全局匹配所有textarea、select等控件,修改成仅匹配带invalid类下的表单控件,避免影响其他页面样式:
.invalid input, .invalid textarea, .invalid select, .invalid checkbox { border-color: red; }
额外注意点
你当前代码中CKEditor绑定的是editorData,没有和note.content同步,会导致content字段的校验失效,可以直接把CKEditor的v-model改成note.content即可:
<ckeditor v-model="note.content" :config="editorConfig" :class="{ 'text-danger invalid': errors.content }"></ckeditor>
内容的提问来源于stack exchange,提问作者tarafikttes
相关产品推荐
相关产品推荐

