foreword
When using the element upload function recently, I found that in the upload componentfile-listIt cannot be updated at the same time, and there is always an empty problem.
Click to see the problem: after the Vue Element UI upload component uploads the file, the file list is still an empty array
Use v-model in vue to solve this synchronization problem (upload, delete can be updated synchronously)
<template>
<el-upload ref='picUpload' v-bind="bindUploadOption" :class="{ hide: hideUpload }" class="upload_box"
:on-change="handleChange" :on-remove="handleRemove">
<slot><i class="el-icon-plus"></i></slot>
</el-upload>
</template>
<script>
export default {
name: "BasicUpload",
data() {
return {
defaultOption: {
"auto-upload": true,
action: '',
limit: 1,
'list-type': 'picture-card',
'show-file-list': true,
data: {
},
class: '',
},
hideUpload: false
}
},
computed: {
bindUploadOption() {
if (this.$attrs.hasOwnProperty('on-change')) {
delete this.$attrs['on-change']
}
if (this.$attrs.hasOwnProperty('on-remove')) {
delete this.$attrs['on-remove']
}
return {
...this.defaultOption,
...this.$attrs
}
}
},
watch: {
'bindUploadOption.fileList': {
handler(nval) {
if (nval.length >= this.bindUploadOption.limit) {
this.hideUpload = true
} else {
this.hideUpload = false
}
},
deep: true
},
},
model: {
prop: 'fileList',
event: 'fileList',
},
methods: {
getUploadRef() {
return this.$refs.picUpload
},
setOtherOption(options) {
this.defaultOption = {
...this.defaultOption,
...options
}
},
handleChange(file, fileList) {
this.$emit("fileList", fileList)
this.$emit("on-change", {
file, fileList })
},
clearFiles() {
this.$emit("fileList", [])
this.$refs.picUpload.clearFiles()
},
handleRemove(file, fileList) {
this.$emit("fileList", fileList)
this.$emit("on-remove", {
file, fileList })
},
}
}
</script>
<style lang="scss" >
.upload_box.hide .el-upload--picture-card {
display: none !important;
}
</style>
analyze
- If the number of pictures uploaded exceeds the limit, the upload button will be hidden
- Notify via hideUpload.
- Two-way binding of filelist through v-model
- Because the upload component needs to actively modify the filelist, the on-change and on-remove methods are processed in the component.
When using it, it needs to be triggered in the form of @.
use
<basic-upload
ref='upload'
:data="itemForm"
:action="`${BASE_URL}uploadImg`"
:limit="1"
v-model="fileList"
list-type="picture-card"
:show-file-list="true"
:headers="headers"
:on-success="handleAvatarSuccess"
@on-remove="handleremove">
</basic-upload>