实现如下内容:
- 选择单个文件,点击手动上传成功
- 选择单个文件,再次选择另外的文件时,覆盖源文件,点击手动上传成功
- 选择单个文件,点击移除,再次选择文件时,点击手动上传新文件成功
常见问题:
- Elementui 版本低时,el-upload组件没有内置:limit限制,通过现有方法控制实现
- 在el-upload提供的onChange或onRemove方法中,如果直接使用filelist对象等于赋值,手动上传动作无法触发
- 如果不定义临时变量filelist_temp,在点击手动上传按钮时,无法判定文件是否已选取,无论是否选取,filelist均为空数组。
代码实现如下:
<template>
<div>
<el-upload
ref='upload'
style="width: 100%"
:action="uploadUrl"
:on-remove="handleRemove"
:on-change="handleChange"
:data="uploadData"
:file-list="filelist"
:before-upload="handleBeforeUpload"
:auto-upload="false">
<el-button type="primary" size="small" slot="trigger">选取文件</el-button>
<div slot="tip" class="el-upload_tip">仅支持上传单个文件</div>
</el-upload>
<el-button type="primary" size="small" @click="submitUpload">上传到服务器</el-button>
</div>
</template>
<script>
export default {
data() {
return {
uploadUrl: '',
uploadData: {},
filelist: [],
filelist_temp: [], //仅为判断是否已经上传文件使用
}
},
methods: {
// 附件上传前处理
handleBeforeUpload(file,filelist) {
//处理其他数据
this.uploadData.create_user = ''
this.uploadData.type = ''
},
// 附件移除
handleRemove(file,filelist) {
//this.filelist = filelist //这种方式无法触发手动上传动作
filelist.splice(0,1)
this.file_list_temp = filelist
this.$forceUpdate()
},
// 附件变更、上传成功,上传失败
handleChange(file,filelist) {
if(file.status === 'ready') {
// 附件变更
//this.filelist = filelist //这种方式无法触发手动上传动作
if(filelist.length > 1) {
filelist.splice(0,1)
}
this.file_list_temp = filelist
this.$forceUpdate()
}else if(file.status === 'success') {
this.$message({
type: 'success',
message: '上传附件成功!'
})
}else {
this.$message({
type: 'error',
message: '上传附件失败,请重试!'
})
}
},
// 上传到服务器
submitUpload() {
// if(this.filelist.length > 0) //
if(this.filelist_temp.length > 0) {
this.$refs.upload.submit()
}else {
this.$message({
type: 'info',
message: '请先上传附件!'
})
}
},
}
}
</script>
{{o.name}}
{{m.name}}