vue3 二次封装el-form表单

作者: 简小咖 | 来源:发表于2022-10-20 14:49 被阅读0次

    二次封装el-form,理由无非就是多个地方用同一个表单,懒得重复写校验。

    表单组件

    <template>
      <el-form ref="FormRef" :model="formData" :rules="rules">
        <el-form-item label="名称" prop="name">
          <el-input v-model.trim="formData.name" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="formData.description" />
        </el-form-item>
      </el-form>
    </template>
    <script setup>
    import { ref, reactive } from "vue";
    //  formData 不可以为空
    const props = defineProps({
      formData: {
        type: Object,
        required: true,
      },
    });
    
    const rules = reactive({
      name: [{ required: true, message: "请输入名称", trigger: "blur" }],
    });
    const FormRef = ref();
    
    // 表单校验
    function validate() {
      if (!FormRef.value) return;
      return FormRef.value.validate((valid) => {
        return valid;
      });
    }
    defineExpose({
      validate,
    });
    </script>
    

    组件的使用

    <template>
      <div>
        <base-form ref="baseFormRef" :formData="clientForm" />
        <el-button type="primary" @click="submit">提交</el-button>
       </div>
    </template>
    
    <script setup>
    import { ref } from "vue";
    import BaseForm from "./components/BaseForm.vue";
    
    const loading = ref(false);
    const baseFormRef = ref();
    
    const clientForm = ref({
      name: "",
      address: "",
      description: "",
    });
    
    const submit = async () => {
      if (await baseFormRef.value.validate()) {
          loading.value = true;
          console.log("校验通过", clientForm.value)
      } else {
        $error("有错误,请检查填写内容!");
      }
    };
    
    </script>
    
    

    相关文章

      网友评论

        本文标题:vue3 二次封装el-form表单

        本文链接:https://www.haomeiwen.com/subject/ifcrartx.html