1 Problem Description
- The status quo
There is a file upload function in the form, before the file is not selected, the form is verified, indicating that the file is not uploaded, the file needs to be uploaded; Select file but not uploaded, verify the form, still prompt file not uploaded, need to upload the file.
Verification result before uploading files
Verification result after uploading files
- expect
Before the file is not selected, the form is verified, indicating that the file is not uploaded and needs to be uploaded. Select file but not uploaded, verify form, should pass validation.
2 Solution
2.1 Ignored but useful for solving the problemElementUI
function
-
The el-upload component has several functional hooks to report the status of file upload/deletion. On-change indicates the hook when the status of the file changes, and on-remove indicates the hook when the file list removes the file.
-
In addition to the validate method, the el-Form component validates some form fields with a validateField method
2.2 Solutions
- When uploading files, in
el-upload
theon-change
Hook function, save the uploaded file, and callel-form
thevalidateField
Function ofel-upload
The binding ofprop
Field verification - File list when removing files in
el-upload
theon-remove
Hook function, iffileList
If null, set the correspondingprop
Is null, and el-form is calledthe
validateFieldFunction of
el-uploadThe binding of
The prop ‘field is verified
3 Code Implementation
<template> <el-form ref="exampleForm" :model="formModel" :rules="rules"> <el-form-item label=" upload file" prop="file"> <el-upload ref="fileUpload" :action="fileUploadUrl" :auto-upload="false" :on-change="fileChange" :on-remove="fileRemove" :file-list="fileList" :limit="1" accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf"> <el-button slot="trigger" </el-button> <span slot="tip" style="margin-left: 20 px "> can only upload the doc/docx/XLS/XLSX/PPT/PPTX/PDF files < / span > < / el - upload > < / el - form - item > < / el - form > < / template > < script > export default { name: 'ExampleForm', data () { return { formModel: { file: null }, rules: { file: [ { required: True, message: 'Please select at least one product tag ', trigger: 'change'}]}, fileUploadUrl: "upload URL"}}, methods: { fileChange(uploadFile, fileList) { this.formModel.file = uploadFile if (fileList.length ! == 0) { this.$refs.exampleForm.validateField('file') } }, fileRemove(uploadFile, fileList) { if (fileList.length === 0) { this.formModel.file = null this.$refs.exampleForm.validateField('file') } } } } </script>Copy the code