vant 上传头像

<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>

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容