<template>
<div class="upload">
<div class="section">
<el-upload
:action="uploadUrl()"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
</div>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
import { mixin } from '../mixins'
export default {
name: 'upload',
mixins: [mixin],
data () {
return {
imageUrl: ''
}
},
computed: {
...mapGetters([
'userId'
])
},
methods: {
uploadUrl () {
return `${this.$store.state.configure.HOST}/user/avatar/update?id=${this.userId}`
},
handleAvatarSuccess (res, file) {
if (res.code === 1) {
this.imageUrl = URL.createObjectURL(file.raw)
this.$store.commit('setAvator', res.avator)
this.notify('上传成功', 'success')
} else {
this.notify('上传失败', 'error')
}
},
beforeAvatarUpload (file) {
const isJPG = file.type === 'image/jpeg'
const isLt2M = file.size / 1024 / 1024 < 10
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!')
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 10MB!')
}
return isJPG && isLt2M
}
}
}
</script>
<style scoped>
.upload {
width: 100%;
}
.section {
height: 600px;
background-color: #e6ecf0;
display: flex;
justify-content: center;
align-items: center;
}
</style>
|