message-image.vue 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <template>
  2. <div
  3. class="image-container"
  4. @click="handleImagePreview"
  5. >
  6. <image
  7. class="message-image"
  8. mode="aspectFit"
  9. :src="props.content.url"
  10. :style="{ width: imageStyles.width, height: imageStyles.height }"
  11. @load="imageLoad"
  12. />
  13. </div>
  14. </template>
  15. <script lang="ts" setup>
  16. import { watchEffect, ref } from '../../../../adapter-vue';
  17. import type { IMessageModel } from '@tencentcloud/chat-uikit-engine';
  18. import type { IImageMessageContent } from '../../../../interface';
  19. interface IProps {
  20. content: IImageMessageContent;
  21. messageItem: IMessageModel;
  22. }
  23. interface IEmit {
  24. (key: 'previewImage'): void;
  25. }
  26. const emits = defineEmits<IEmit>();
  27. const props = withDefaults(
  28. defineProps<IProps>(),
  29. {
  30. content: () => ({}),
  31. messageItem: () => ({} as IMessageModel),
  32. },
  33. );
  34. const DEFAULT_MAX_SIZE = 155;
  35. const imageStyles = ref({ width: 'auto', height: 'auto' });
  36. const genImageStyles = (value: { width?: any; height?: any }) => {
  37. const { width, height } = value;
  38. if (width === 0 || height === 0) {
  39. return;
  40. }
  41. let imageWidth = 0;
  42. let imageHeight = 0;
  43. if (width >= height) {
  44. imageWidth = DEFAULT_MAX_SIZE;
  45. imageHeight = (DEFAULT_MAX_SIZE * height) / width;
  46. } else {
  47. imageWidth = (DEFAULT_MAX_SIZE * width) / height;
  48. imageHeight = DEFAULT_MAX_SIZE;
  49. }
  50. imageStyles.value.width = imageWidth + 'px';
  51. imageStyles.value.height = imageHeight + 'px';
  52. };
  53. watchEffect(() => {
  54. genImageStyles(props.content);
  55. });
  56. const imageLoad = (event: Event) => {
  57. genImageStyles(event.detail);
  58. };
  59. // 预览
  60. const handleImagePreview = () => {
  61. if (props.messageItem?.status === 'success' || props.messageItem.progress === 1) {
  62. emits('previewImage');
  63. }
  64. };
  65. </script>
  66. <style lang="scss" scoped>
  67. .image-container {
  68. position: relative;
  69. background-color: #f4f4f4;
  70. // 防止div被撑高
  71. font-size: 0;
  72. .message-image {
  73. max-width: 150px;
  74. }
  75. }
  76. </style>