<template>
<div class="fileUpload">
<!--
组件使用:
1、结构
<file-upload ref="uploadCom" @successHandle="fileUploadComplete" />
<el-button @click="uploadFile">上传文件</el-button>
2、逻辑
/* 上传图片 */
uploadFile: function () {
this.$refs.uploadCom.$refs['el-upload'].submit()
},
/* 图片上传成功后回调 */
fileUploadComplete: function (data) {
console.log('文件上传成功,文件路径集合', data)
}
-->
<el-upload
list-type="picture-card"
ref="el-upload"
:disabled="disabled"
:action="uploadUrl"
:file-list="fileListOrg"
:multiple="fileConfig.multiple"
:headers="fileConfig.headers"
:limit="fileConfig.limit"
:data="fileConfig.data"
:auto-upload="fileConfig.autoUpload"
:on-change="fileChange"
:on-success="fileSuccess"
:on-remove="fileRemove"
:on-error="fileError"
:on-exceed="limitNum"
>
<i slot="default" class="el-icon-plus">上传</i>
</el-upload>
</div>
</template>
<script>
// import {map} from '../api/map.js'
export default {
name: 'fileUpload',
props: {
imgUrl: { // 图片会显示时,路径集合
type: Array
}
},
data () {
return {
fileSuccessNum: 0, // 多个文件时,上传成功的文件数量
disabled: false, // 是否禁用上传组件,只做展示
uploadUrl: '', // 上传服务器地址
fileListOrg: [], // 文件原列表(本地文件)
fileListCurrent: [], // 文件上传成功后,存储文件
fileUrlArr: [], // 文件上传成功后,存储文件路径
fileConfig: { // 文件上传相关配置
multiple: false,
limit: 5,
headers: {},
data: {}, // 上传额外参数
/* // 测试数据
headers: {
token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJtb2JpbGUiOiI0ODEiLCJleHAiOjE2MTE4MTI4MzR9.X5zyf6jvuSbt6gBUkkkcQ2zbmQDZ3jL_4MS5InnTOyc'
},
// 测试数据
data: {
oldUrl: ''
}, */
autoUpload: false
}
}
},
created:function(){
if (this.imgUrl.length) {
this.showImg(this.imgUrl)
}
},
methods:{
showImg:function(imgUrl){
let showList = []
let urlList = []
for (let i = 0;i < imgUrl.length;i++) {
showList.push({
uid: new Date().getTime() + i,
name: imgUrl[i],
status: 'done',
url: imgUrl[i],
size: 666666,
fileType: ''
})
urlList.push(imgUrl[i])
}
this.fileListOrg = showList
this.fileUrlArr = urlList
this.fileSuccessNum = imgUrl.length
},
fileChange: function (file, fileList) {
this.fileListOrg = fileList
},
fileSuccess:function(res, file, fileList) {
if (res.errcode == 10000) {
// 上传成功
this.fileUrlArr.push(res.data.path)
this.fileSuccessNum ++
this.fileListOrg.forEach((item, inx) => {
if (file.name == item.name) {
file.url = res.data.path
this.$set(this.fileListOrg, inx, file)
}
})
if (this.fileSuccessNum == this.fileListOrg.length) {
this.$emit('successHandle', this.fileUrlArr)
}
}
},
fileRemove:function(file, fileList) {
this.fileListOrg = fileList
this.fileUrlArr = this.fileUrlArr.filter(item => file.url != item)
this.fileSuccessNum = this.fileUrlArr.length
},
fileError:function(e) {
console.log('文件上传出错!')
},
limitNum: function () {
this.$message({
message: `最多可上传${this.fileConfig.limit}张图片`,
type: 'error'
})
}
},
}
</script>
<style scoped>
</style>
element图片上传组件封装
最新推荐文章于 2024-06-11 17:55:14 发布