话不多说,直接上代码
// template
<el-upload
drag
multiple
action=""
:on-change="fileChange"
:on-remove="fileRemove"
:auto-upload="false"
:file-list="fileList"
>
</el-upload>
<button @click="saveBtnClick">确定上传</button>
// script
data() {
return {
fileList: [],
isRepeat: true, // 用来记录上传的文件是否重复
}
},
watch: {
isRepeat(newValue) {
if(newValue) {
this.debouncedTip()
}
}
},
created() {
// _.debounce借用lodash的防抖函数,避免一次有多个重复文件,弹窗多次弹出
this.debouncedTip = _.debounce(function() {
this.$message.waring('已删除重复文件')
}, 200)
}
methods: {
// 文件状态改变时的钩子
fileChange(file, fileList) {
// 删除重复上传文件
for(let i = 0; i < fileList.length - 1; i += 1) {
for(let j = 0; j < fileList.length; j += 1) {
if(fileList[i].name === fileList[j].name) {
fileList.splice(i ,1)
this.isRepeat = true
break
}
}
}
this.fileList = fileList
// 避免值在同一个事件队列中被一次性更新,这样会监听不到isRepeat的更改
this.$nextTick(() => {
this.isRepeat = false
})
},
// 上传文件删除时调用
fileRemove(file, fileList) {
this.fileList = fileList
},
async saveBtnClick() {
if(this.fileList.length === 0) {
this.$message.warning('请先选择上传文件!')
return
}
await this.uploadFile()
},
// 文件上传方法
async uploadFile() {
// 上传文件要使用FormData形式
const formData = new FormData()
this.fileList.forEach((file) => {
formData.append('file', file.raw)
})
const res = await this.uploadFileMethods({
file: formData
})
},
// 和后台对接的上传方法
uploadFileMethods(payload) {
axios.post(
url: 'xx',
payload.file,
// 设置请求头
{
'Content-Type': 'multipart/form-data',
}
)
}
}
如有错误,欢迎指正!