Mastering Element UI Upload Component in Vue 2 Applications
Configuring the <el-upload> component within a Vue 2 project involves binding specific properties to manage state, validation, and server communication. The following template demonstrates a setup that supports drag-and-drop, limits file count, and defers automatic transmission.
<template>
<el-upload
ref="fileImporter"
class="import-container"
:action="serverEndpoint"
:data="requestPayload"
:file-list="documentQueue"
:limit="1"
:auto-upload="false"
:on-change="inspectFile"
:on-success="processResponse"
:on-remove="discardFile"
accept=".xlsx, .xls"
drag
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">
Drag file here or <em>click to select</em>
</div>
<div slot="tip" class="el-upload__tip">
Only Excel files (.xls/.xlsx) are supported
</div>
</el-upload>
</template>
Component Configuration Breakdown
The properties defined above govern the interaction model:
ref: Assigns a local reference to the component instance, enabling programmatic control viathis.$refs.action: Defines the target URL for the HTTP POST request.data: Appends additional parameters to the form data payload.limit: Restricts the maximum number of files allowed in the queue.accept: Hints to the browser which file types to display in the selection dialog.auto-upload: Whenfalse, files are added to the list but require a manual trigger to send the request.file-list: Binds the internal state to a reactive array for external management.drag: Enables the drop zone interaction mode.
Managing Instance Methods via Ref
Utilizing the ref attribute allows direct invocation of internal methods. This is critical when auto-upload is disabled.
this.$refs.fileImporter.submit(): Initiates the upload process for files current in the list.this.$refs.fileImporter.clearFiles(): Resets the internal file list without triggering a server request.
Caution is advised when relying heavily on ref for communication, as it creates tight coupling between parent and child components.
Validation Strategy: Accept vs. On-Change
While the accept property filters visible files in the OS dialog, it does not prevent all invalid selections across different browsers, nor does it provide user feedback if a file is blocked silently. Consequently, relying solely on accept may result in a scenario where on-change does not fire if the browser filters the file before selection.
To ensure robust validation and user feedback, implement logic within the on-change handler. This allows the application to intercept the file object, verify extensions or MIME types, and display error messages explicitly.
inspectFile(file) {
const validExtensions = ['xls', 'xlsx'];
const fileName = file.name.toLowerCase();
const extension = fileName.slice(fileName.lastIndexOf('.') + 1);
if (!validExtensions.includes(extension)) {
this.$message.error('Invalid format. Please upload an Excel file.');
// Remove the invalid file from the list immediately
this.$refs.fileImporter.clearFiles();
return false;
}
return true;
}
Handling Resposne and State
The success callback manages the server response and UI state cleanup. It is essential to verify the business logic status code, not just the HTTP status.
processResponse(res, file, list) {
if (res.code === 200) {
this.$message.success(res.message || 'Upload completed');
this.dialogVisible = false;
} else {
this.$message.error(res.message || 'Upload failed');
}
// Clear the list after processing to allow re-upload
this.$refs.fileImporter.clearFiles();
}
File List and Removal
The file-list prop synchronizes the component with a local array. When a user clicks the remove icon, the on-remove event triggers. The handler should update the local state to reflect the removal, ensuring data consistency between the UI and the application logic.
Controlling Upload Trigger
Setting auto-upload to false decouples file selection from transmission. This pattern is useful when multiple parameters need to be finalized before sending the request. The developer must explicitly call the submit method via the component reference when the user confirms the action.