UpdatePhoto.vue 1.77 KB
<template>
  <div class="updatePhoto_container">
    <NafmHeader title=" " :showBack="true" bgColor="#000" @onBack="$emit('close')">
      <template slot="right">
        <span class="finish" @click="handleSave">{{$t('button.save')}}</span>
      </template>
    </NafmHeader>
    <img :src="image" ref="image" class="image">
  </div>
</template>
<script>
import 'cropperjs/dist/cropper.css';
import Cropper from 'cropperjs';
export default {
  name: 'UpdataPhoto',
  props: {
    file: {
      required: true
    }
  },
  data() {
    return {
      image: window.URL.createObjectURL(this.file),
      cropper: null,
    }
  },
  mounted() {
    const image = this.$refs.image;
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    });
  },
  methods: {
    async getCroppedCanvas() {
      return new Promise(resolve => {
        this.cropper.getCroppedCanvas().toBlob((file) => {
          resolve(file)
        })
      })
    },
    async handleSave() {
      // 图片上传 格式Content-Type: multipart/form-data,则一定要提交FormatData对象
      const fd = new FormData()
      //   fd.append('photo', this.file)
      const file = await this.getCroppedCanvas()
      fd.append('photo', file)

      // api 调用 todo

      // 更新父组件
      this.$emit('upDataPhoto', window.URL.createObjectURL(file))

      // 关闭弹出层
      this.$emit('close')

      // 保存成功
      Toast('保存成功')
    }
  }
}
</script>
<style lang="less" scoped>
.updatePhoto_container {
  height: 100vh;
  background: #000;
}
/deep/ .cropper-view-box {
  border-radius: 50%;
}
.image {
  display: block;
  max-width: 100%;
}
</style>