AuthImage.vue 1.6 KB

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