前言
最近在使用element 上传功能的时候,发现upload组件中的file-list不能同时更新,一直出现为空的问题.
点击可见问题: Vue Element UI upload 组件上传文件之后 file list 依旧是空数组
使用vue中v-model来解决这个同步的问题(实现上传,删除可以同步更新)
<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>
分析
- 包含上传的图片数量超过限制数量会隐藏上传按钮
- 通过hideUpload 来通知.
- 通过v-model 实现filelist 双向绑定
- 因为upload组件需要主动去修改filelist, 所以在组件中处理了on-change和on-remove方法.
使用的时候需要通过@的形式触发.
使用
<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>