vue3+ant design vue实现表单及文件上传必输项设置校验~

1、需求:表单与文件上传设置必输项校验

2、思路:直接将文件上传放在form表单中,特别注意需要将文件列表定义在表单数据中或进行转存,否则会有2个数据来源,数据校验就检测不到文件列表的变化,造成无法同时校验。

3、代码

<a-form
      ref="form"
      :model="formState"
      :label-col="{ span: 8 }"
      :wrapper-col="{ span: 16 }"
      :rules="rules"
    >
      <a-row>
        <a-col :span="18">
          <a-form-item name="xuanzechanpinxian" label="产品" labelAlign="right">
            <a-select v-model:value="formState.xuanzechanpinxian">
              <a-select-option value="1">T</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row style="line-height: 32px">
        <a-col :span="18">
          <a-form-item name="fileList" label="上传文件" labelAlign="right">
            <a-upload
              v-model:file-list="fileList"
              name="文件上传"
              action=""
              :customRequest="upDown"
              :beforeUpload="beforeUpload"
              @remove="removeFile"
              accept=".xlsx,.xls"
            >
              <a-button> 选择文件 </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <a-space style="display: flex; flex-direction: row; justify-content: center">
      <a-button type="primary" @click="submitSure">确定</a-button>
      <a-button @click="cancel">取消</a-button>
    </a-space>


//表单数据
  interface myObject {
    xuanzechanpinxian: string;
    fileList: any[];
  }
  const formState = ref<myObject>({
    xuanzechanpinxian: '', 
    fileList: [],
  });
  const rules = {
    xuanzechanpinxian: [
      {
        required: true,
        trigger: 'change',
      },
    ],
    fileList: [
      {
        required: true,
        message: '请上传文件',
        trigger: 'blur',
      },
    ],
  };


// 文件上传测试
  import { message } from 'ant-design-vue';
  // 检查文件类型,如果文件类型正确,则继续上传,false指停止上传,true指继续上传,file是文件
  const beforeUpload = (file) => {
    //检查文件类型是否为Excel
    const isExcel =
      file.type === 'application/vnd.ms-excel' ||
      file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    if (!isExcel) {
      message.error('只能上传Excel文件!');
      return false;
    }
    return true;
  };
  // 导入文件
  const upDown = async (file) => {
    const random = Math.random();
    const fileName = `${random}${file.file.name}`;
    // OSS上传签名
    queryAutograph({}).then(async (res) => {
      const { host, dir, OSSAccessKeyId, success_action_status, Signature, policy } = res;
      const address = dir + fileName;
      const url = host;
      const formData = new FormData();
      formData.append('key', address);
      formData.append('OSSAccessKeyId', OSSAccessKeyId);
      formData.append('Signature', Signature);
      formData.append('policy', policy);
      formData.append('success_action_status', success_action_status);
      formData.append('file', file.file);
      // 上传OSS
      try {
        await uploadOss({ url, formData });
      } catch (e) {
        message.error('上传失败');
        return;
      }
      //拼接地址
      downloadUrl.value = host + '/' + address;
      let list: any = [];
      list.push({ name: file.file.name, url: downloadUrl });
      fileList.value = list;
      formState.value.fileList = fileList.value; //转存到表单数据中,便于校验
    });
  };
  // 删除文件
  const removeFile = (file) => {
    const index = fileList.value.indexOf(file.file);
    const newFileList = fileList.value.slice();
    newFileList.splice(index, 1);
    fileList.value = newFileList;
    formState.value.fileList = []; //转存到表单数据中,便于校验
  };

//确定
  const form = ref();
  const submitSure = () => {
    form.value
      .validateFields()
      .then((values) => {
        console.log('验证通过,表单数据为:', values);
      })
      .catch((errorInfo) => {
        console.log('验证失败,错误信息为:', errorInfo);
      });
  };

要在 Vue 3 中使用 Ant Design Vue 的 Form 表单组件进行确认密码校验,你可以自定义校验规则来实现。下面是一个示例: ```vue <template> <a-form ref="form" :model="formData"> <a-form-item label="密码" name="password" rules="required"> <a-input type="password" v-model="formData.password" /> </a-form-item> <a-form-item label="确认密码" name="confirmPassword" rules="required,checkPassword"> <a-input type="password" v-model="formData.confirmPassword" /> </a-form-item> <a-form-item> <a-button type="primary" @click="submitForm">提交</a-button> </a-form-item> </a-form> </template> <script> import { ref } from 'vue'; import { Form, Input, Button, message } from 'ant-design-vue'; export default { components: { 'a-form': Form, 'a-form-item': Form.Item, 'a-input': Input, 'a-button': Button }, setup() { const formRef = ref(null); const formData = ref({ password: '', confirmPassword: '' }); const checkPassword = (_, value) => { if (value !== formData.password) { return Promise.reject(new Error('两次密码输入不一致')); } return Promise.resolve(); }; const submitForm = () => { formRef.value.validate((valid) => { if (valid) { // 验证通过,执行表单提交操作 console.log('表单验证通过'); // ... } else { console.log('表单验证失败'); } }); }; return { formRef, formData, checkPassword, submitForm }; } }; </script> ``` 在上述示例中,我们在确认密码字段的 `a-form-item` 组件上定义了一个名为 `checkPassword` 的校验规则。该规则使用了一个自定义校验函数,并在函数内部判断确认密码是否与密码字段的值相同。如果不相同,我们使用 `Promise.reject` 返回一个错误信息,表示校验失败;如果相同,我们使用 `Promise.resolve` 表示校验通过。 然后,我们将这个校验规则 `checkPassword` 应用到确认密码字段的 `rules` 属性中,通过逗号分隔多个规则。注意,我们还将 "required" 规则也应用到了确认密码字段上,以确保确认密码不能为空。 在 `submitForm` 方法中,我们使用 `formRef.value.validate` 方法来进行表单验证,当验证完成后执行回调函数。你可以在回调函数中处理验证通过和验证失败的情况。 希望以上信息对你有帮助!如果你还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值