面试题答案
一键面试- 在Vue组件中定义数据和验证规则:
<template> <form @submit.prevent="submitForm"> <label for="fieldA">字段A:</label> <input type="text" id="fieldA" v-model="formData.fieldA"> <label for="fieldB">字段B:</label> <input type="text" id="fieldB" v-model="formData.fieldB"> <button type="submit">提交</button> </form> </template> <script> export default { data() { return { formData: { fieldA: '', fieldB: '' }, rules: { fieldA: [], fieldB: [(rule, value, callback) => { if (this.formData.fieldA === '特定字符串') { if (!value) { callback(new Error('字段B必填')); } else if (isNaN(Number(value))) { callback(new Error('字段B必须为数字')); } else { callback(); } } else { callback(); } }] } }; }, methods: { submitForm() { this.$refs.form.validate((valid) => { if (valid) { console.log('表单验证通过'); } else { console.log('表单验证失败'); } }); } } }; </script> <style scoped> </style>
- 在模板中使用
el - form
和el - input
(假设使用Element - UI,也可使用原生HTML结合自定义验证逻辑):<template> <el - form ref="form" :model="formData" :rules="rules"> <el - form - item prop="fieldA"> <el - input v - model="formData.fieldA" placeholder="字段A"></el - input> </el - form - item> <el - form - item prop="fieldB"> <el - input v - model="formData.fieldB" placeholder="字段B"></el - input> </el - form - item> <el - button type="primary" @click="submitForm">提交</button> </el - form> </template>
上述代码首先在Vue组件的data
中定义了表单数据formData
和验证规则rules
。在rules
中,针对fieldB
的验证函数根据fieldA
的值来决定fieldB
是否必填且必须为数字。在模板中展示了两种方式,一种是原生HTML表单结合自定义验证逻辑,另一种是使用Element - UI的表单组件结合验证规则。submitForm
方法用于触发表单验证。