index.vue 1.7 KB

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