LazyImage.vue 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <template>
  2. <image
  3. :src="lazyLoad ? placeholderSrc : realSrc"
  4. :mode="mode"
  5. :class="['lazy-image', { 'loaded': isLoaded }]"
  6. @load="onLoad"
  7. @error="onError"
  8. @click="onClick"
  9. />
  10. </template>
  11. <script setup lang="ts">
  12. import { ref, watch, onMounted } from 'vue';
  13. interface Props {
  14. src: string;
  15. mode?: string;
  16. placeholder?: string;
  17. lazyLoad?: boolean;
  18. }
  19. const props = withDefaults(defineProps<Props>(), {
  20. mode: 'aspectFill',
  21. placeholder: '',
  22. lazyLoad: true,
  23. });
  24. const emit = defineEmits<{
  25. load: [event: any];
  26. error: [event: any];
  27. click: [event: any];
  28. }>();
  29. const isLoaded = ref(false);
  30. const realSrc = ref('');
  31. const placeholderSrc = props.placeholder || '/static/placeholder.png';
  32. // 监听 src 变化
  33. watch(() => props.src, (newVal) => {
  34. if (newVal && props.lazyLoad) {
  35. // 使用 uni-app 的懒加载
  36. realSrc.value = newVal;
  37. } else if (newVal) {
  38. realSrc.value = newVal;
  39. }
  40. }, { immediate: true });
  41. function onLoad(event: any) {
  42. isLoaded.value = true;
  43. emit('load', event);
  44. }
  45. function onError(event: any) {
  46. console.error('[LazyImage] 图片加载失败:', props.src);
  47. emit('error', event);
  48. }
  49. function onClick(event: any) {
  50. emit('click', event);
  51. }
  52. </script>
  53. <style scoped>
  54. .lazy-image {
  55. opacity: 0;
  56. transition: opacity 0.3s ease;
  57. }
  58. .lazy-image.loaded {
  59. opacity: 1;
  60. }
  61. </style>