MST

星途 面试题库

面试题:Vue表单绑定中复杂表单验证逻辑之联动验证

在Vue表单绑定场景下,有两个表单字段A和B,当A的值为某个特定字符串时,B字段必填且必须为数字。请描述如何通过Vue的表单验证机制来实现这一复杂逻辑,写出关键代码片段。
30.3万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试
  1. 在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>
    
  2. 在模板中使用 el - formel - 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方法用于触发表单验证。