1.首页使用el-image显示数据,用的是转base64后端返给的
<el-table-column prop="avatar" align="center" label="头像">
<template #default="scope">
<el-image style="height: 40px;width: 40px;" :src="scope.row.avatar"></el-image>
</template>
</el-table-column>
private url = 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'
2.在添加的页面上的操作
//写好组件
<el-upload class="upload-demo" ref="upload" action="" :on-remove="handleRemove" :file-list="file_list" :on-change="getFile"
:auto-upload="false" list-type="picture" :limit="1">
<el-button size="small" type="primary">上传人物头像</el-button>
</el-upload>
//存放base64最后放接口里的
private icon: any = ''
//存放图片的list
private file_list: any[] = []
// 移除上传的文件时的回调
private handleRemove() {
this.icon = ''
this.$delete(this.file_list, 0)
}
// 图片转base64 核心
private getBase64(file) {
return new Promise(function (resolve, reject) {
let reader = new FileReader()
let imgResult = ''
reader.readAsDataURL(file)
reader.onload = function () {
imgResult = reader.result as any
}
reader.onerror = function (error) {
reject(error)
}
reader.onloadend = function () {
resolve(imgResult)
}
})
}
// 当文件状态改变、添加文件、上传成功和上传失败时调用,控制大小和类型
private getFile(file, fileList) {
let fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
let fileSize = file.size / 1024 / 1024 < 5
if (fileType !== 'png' && fileType !== 'jpg' && fileType !== 'jpeg') {
;(this.$refs.upload as any).clearFiles()
ElMessage({
message: '上传文件只能是 .png、.jpg、jpeg格式!',
type: 'warning'
})
return false
} else if (!fileSize) {
;(this.$refs.upload as any).clearFiles()
ElMessage({
message: '上传文件大小不能超过 5MB!',
type: 'warning'
})
return false
} else {
// this.isImage = true
this.getBase64(file.raw).then((res) => {
this.icon = res
})
}
}
//再打开编辑的时候需要的操作
//判断带过来的图片有没有base64数据,有就返回它,在dialog显示,没有就清空,解决空白图片问题
if (rowData.avatar) {
this.file_list = [{ url: rowData.avatar }]
} else {
this.file_list = []
}