提供一个封装element组件库的带标题的图片上传组件示例
时间: 2023-04-01 07:03:48 浏览: 125
好的,我可以回答这个问题。以下是一个封装element组件库的带标题的图片上传组件示例:
```
<template>
<div>
<el-upload
class="upload-demo"
action="/upload"
:on-success="handleSuccess"
:before-upload="beforeUpload"
:file-list="fileList"
:headers="headers"
:data="formData"
:multiple="false"
:show-file-list="false"
>
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
<div class="preview">
<img v-if="imageUrl" :src="imageUrl" alt="" />
</div>
</div>
</template>
<script>
export default {
data() {
return {
fileList: [],
imageUrl: '',
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token'),
},
formData: {
type: 'avatar',
},
};
},
methods: {
handleSuccess(response, file, fileList) {
this.imageUrl = URL.createObjectURL(file.raw);
},
beforeUpload(file) {
const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
const isLt500K = file.size / 1024 < 500;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
}
if (!isLt500K) {
this.$message.error('上传头像图片大小不能超过 500KB!');
}
return isJPG && isLt500K;
},
},
};
</script>
<style scoped>
.upload-demo {
display: inline-block;
margin-right: 20px;
}
.preview {
margin-top: 20px;
}
.preview img {
max-width: 200px;
}
</style>
```
阅读全文