el-upload多图上传 多文件上传 on-change事件多次触发问题解决
在使用 el-upload上传文件时,on-change会触发二次事件,一次是ready状态,一次是success状态
<div id="app">
<el-upload action="https://jsonplaceholder.typicode.com/posts/" :show-file-list="true" :file-list="fileList"
:on-change="imageFileChange" ref="uploadFileRef" multiple>
<el-button size="mini" style="margin-right:10px">上传文件</el-button>
</el-upload>
</div>
<script>
let app = new Vue({
el: "#app",
data() {
return {
fileList: [],
uploadLoading: null
}
},
methods: {
imageFileChange(file, fileList) {
console.log(fileList[0].status);
console.log(new Date().toLocaleString());
}
}
})
</script>
触发success状态的原因是开启了自动上传 :auto-upload="true"
,关闭自动上传就不会触发success了。
但我们上传多张图片时,只想一次性上传完,而不是触发一次 on-change事件就上传一次,那要怎么做呢?
方法就是防抖
imageFileChange(file, fileList) {
if (file.status !== 'ready') return // 阻止上传成功的触发
console.log(file.status)
if (this.timer) return
this.timer = setTimeout(() => {
this.$confirm('是否覆盖上传?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
this.uploadLoading = this.$loading({
lock: true,
text: '上传中',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
});
this.$refs.uploadFileRef.submit()
}).catch(() => {
}).finally(() => {
this.uploadLoading.close()
this.timer = null
})
},100)
}