index.vue 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <template>
  2. <view class="hc-img-view" :style="{'width':widths,'height':heights,'aspect-ratio':aspectRatio,'background-image':srcs}">
  3. <image class="image-bar" :src="url" @error="imgError" @load="imgLoad"/>
  4. <view class="bg-gray-1 hc-flex-center h-full radius" v-if="!isImage">
  5. <view class="p-1 text-gray-4">
  6. <view class="text-40 text-center">
  7. <text class="i-ri-emotion-sad-line"/>
  8. </view>
  9. <view class="text-22">加载失败</view>
  10. </view>
  11. </view>
  12. </view>
  13. </template>
  14. <script setup>
  15. import {onMounted, ref, watch} from "vue";
  16. const props = defineProps({
  17. 'src': String,
  18. 'width': [String, Number],
  19. 'height': [String, Number]
  20. });
  21. //初始变量
  22. const srcs = ref('');
  23. const widths = ref('');
  24. const heights = ref('');
  25. const aspectRatio = ref('');
  26. //图片Url
  27. const url = ref(props.src);
  28. const isImage = ref(true)
  29. //加载完成
  30. onMounted(() => {
  31. setStyleData(props.width, props.height);
  32. });
  33. //监听变化
  34. watch(() => [
  35. props.src,
  36. props.width,
  37. props.height
  38. ], ([src, width, height]) => {
  39. url.value = src;
  40. setStyleData(width, height);
  41. })
  42. //设置样式
  43. const setStyleData = (width, height) => {
  44. widths.value = (width * 2) + 'rpx';
  45. heights.value = (height * 2) + 'rpx';
  46. aspectRatio.value = 'auto ' + width + ' / ' + height;
  47. }
  48. //图片加载失败
  49. const imgError = () => {
  50. srcs.value = '';
  51. isImage.value = false
  52. }
  53. //图片载入完毕
  54. const imgLoad = () => {
  55. srcs.value = `url(${url.value})`;
  56. isImage.value = true
  57. }
  58. </script>
  59. <style lang="scss" scoped>
  60. .hc-img-view {
  61. background-position: 0% 0%;
  62. background-size: 100% 100%;
  63. display: inline-block;
  64. .image-bar {
  65. position: absolute;
  66. width: 0;
  67. height: 0;
  68. will-change: transform
  69. }
  70. }
  71. </style>