<template>
<div class="container">
<van-uploader
ref="fileListRef"
v-model="fileList"
:before-read="beforeRead"
:after-read="afterRead"
:preview-full-image="false"
:deletable="false"
:max-count="1"
>
<img v-if="imgSrc" class="img" :src="imgSrc" alt="">
<img v-else class="img" :src="require('@img/timg.jpg') " alt="">
</van-uploader>
</div>
</template>
<script>
import uploadApi from '@/api/common'
import { mapGetters } from 'vuex'
export default {
name: 'UploadImg',
props: {
isWho: { // 雇主1 公司2 求职者3
type: String || Number,
default: '1'
},
photo: {
type: String,
default: ''
}
},
data() {
return {
fileList: [],
avatorImg: {},
urlName: '',
imgSrc: ''
}
},
computed: {
...mapGetters(['userInfo'])
},
watch: {
photo(val) {
this.$nextTick(() => {
this.imgSrc = val
})
}
},
created: function() {
this.urlName = this.$route.name
this.imgSrc = this.photo
},
methods: {
beforeRead(file) {
const url = window.URL || window.webkitURL || window.mozURL
const src = url.createObjectURL(file) // 本地临时的地址
this.imgSrc = src
return true
},
afterRead(file) {
const slefFormData = new window.FormData()
slefFormData.append('file', file.file)
this.$toast.loading({
duration: 12000,
forbidClick: true
})
uploadApi.uploadImg(slefFormData).then(res => {
if (res.code === 0) {
this.avatorImg = res.body.absoluteUrl
this.imgSrc = res.body.absoluteUrl
this.$emit('sendImg', this.avatorImg)
const userInfo = {
...this.userInfo,
avatorImg: this.avatorImg
}
this.$store.dispatch('app/setUserInfo', userInfo)
this.$toast.success('Upload successful')
} else {
this.imgSrc = ''
this.$toast.fail('Upload failed')
}
}).catch(() => {
this.imgSrc = ''
this.$toast.fail('Upload failed')
})
this.$nextTick(() => {
this.$refs.fileListRef.deleteFile(file, 0)
})
}
}
}
</script>
网友评论