<template>
  <img ref="img" style="margin:0 auto;border-radius: 4px;" :style="{ width: imageWidth, height:imageHeight}"></img>
</template>
<script>
import { getToken } from '@/utils/auth'
export default {
  name: "AuthImg",
  props: {
    authSrc: {
      type: String,
      default: "",
    },
    imageWidth: {
      type: [Number, String]
    },
    imageHeight: {
      type: [Number, String]
    }
  },
  mounted () {
    let token = getToken()
    Object.defineProperty(Image.prototype, 'authsrc', {
      writable: true,
      enumerable: true,
      configurable: true
    })
    let img = this.$refs.img
    let request = new XMLHttpRequest();
    request.responseType = 'blob';
    request.open('get', this.authSrc, true);
    request.setRequestHeader('Authorization', 'Bearer '+token);  //根据后端需求添加的权限标志
    request.onreadystatechange = e => {
      if (request.readyState == XMLHttpRequest.DONE && request.status == 200) {
        img.src = URL.createObjectURL(request.response);
        img.onload = () => {
          URL.revokeObjectURL(img.src);
        }
      }
    };
    request.send(null);
  }
}
</script>
