AuthImage.vue 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <template>
  2. <img :src="src" @onload="onload" @click="$emit('click')" />
  3. </template>
  4. <script>
  5. export default {
  6. props: {
  7. authSrc: {
  8. type: String,
  9. default: null,
  10. },
  11. },
  12. emits: ['click'],
  13. data: function () {
  14. return {
  15. src: '',
  16. };
  17. },
  18. watch: {
  19. authSrc: function (newValue, oldValue) {
  20. if (newValue != oldValue) {
  21. this.loadImage(newValue);
  22. }
  23. },
  24. },
  25. mounted: function () {
  26. this.noImage = '/static/assets/client-base-v4/image/no-image.png';
  27. this.errorImage = '/static/assets/client-base-v4/image/load-error.png';
  28. this.loadingImage = '/static/assets/client-base-v4/image/loading.gif';
  29. this.src = this.loadingImage;
  30. this.loadImage(this.authSrc);
  31. },
  32. methods: {
  33. loadImage: function (url) {
  34. let _self = this;
  35. if (url == null || url == '') {
  36. _self.src = this.noImage;
  37. return;
  38. }
  39. this.src = this.loadingImage;
  40. fetch(url, {
  41. method: 'GET',
  42. cache: 'default',
  43. headers: {
  44. 'token': localStorage.getItem('#token'),
  45. 'Cache-Control': 'max-age=2592000',
  46. },
  47. }).then(res => res.blob())
  48. .then(blob => {
  49. _self.src = URL.createObjectURL(blob);
  50. })
  51. .catch(err => {
  52. console.error(err);
  53. });
  54. // let request = new XMLHttpRequest();
  55. // request.responseType = 'blob';
  56. // request.open('get', url, true);
  57. // request.setRequestHeader(
  58. // 'token', localStorage.getItem('#token'),
  59. // );
  60. // request.setRequestHeader(
  61. // 'Cache-Control', 'max-age=3600',
  62. // );
  63. // request.onload = function (e) {
  64. // if (this.status == 200) {
  65. // _self.src = URL.createObjectURL(this.response);
  66. // } else {
  67. // _self.src = _self.errorImage;
  68. // }
  69. // };
  70. // request.send(null);
  71. },
  72. /**
  73. * 图片加载完毕,调用本方法,释放通过URL.createObjectURL()创建的对象URL
  74. */
  75. onload: function () {
  76. let _self = this;
  77. URL.revokeObjectURL(_self.src);
  78. },
  79. },
  80. };
  81. </script>