wxParseImg.vue 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <template>
  2. <image
  3. :mode="node.attr.mode"
  4. :lazy-load="node.attr.lazyLoad"
  5. :class="node.classStr"
  6. :style="newStyleStr || node.styleStr"
  7. :data-src="node.attr.src"
  8. :src="node.attr.src"
  9. @tap="wxParseImgTap"
  10. @load="wxParseImgLoad"
  11. />
  12. </template>
  13. <script>
  14. export default {
  15. name: 'wxParseImg',
  16. data() {
  17. return {
  18. newStyleStr: '',
  19. preview: true,
  20. };
  21. },
  22. props: {
  23. node: {
  24. type: Object,
  25. default() {
  26. return {};
  27. },
  28. },
  29. },
  30. methods: {
  31. wxParseImgTap(e) {
  32. if (!this.preview) return;
  33. const { src } = e.currentTarget.dataset;
  34. if (!src) return;
  35. let parent = this.$parent;
  36. while(!parent.preview || typeof parent.preview !== 'function') {// TODO 遍历获取父节点执行方法
  37. parent = parent.$parent;
  38. }
  39. parent.preview(src, e);
  40. },
  41. // 图片视觉宽高计算函数区
  42. wxParseImgLoad(e) {
  43. const { src } = e.currentTarget.dataset;
  44. if (!src) return;
  45. const { width, height } = e.mp.detail;
  46. const recal = this.wxAutoImageCal(width, height);
  47. const { imageheight, imageWidth } = recal;
  48. const { padding, mode } = this.node.attr;
  49. const { styleStr } = this.node;
  50. const imageHeightStyle = mode === 'widthFix' ? '' : `height: ${imageheight}px;`;
  51. this.newStyleStr = `${styleStr}; ${imageHeightStyle}; width: ${imageWidth}px; padding: 0 ${+padding}px;`;
  52. },
  53. // 计算视觉优先的图片宽高
  54. wxAutoImageCal(originalWidth, originalHeight) {
  55. // 获取图片的原始长宽
  56. const { padding } = this.node.attr;
  57. const windowWidth = this.node.$screen.width - (2 * padding);
  58. const results = {};
  59. if (originalWidth < 60 || originalHeight < 60) {
  60. const { src } = this.node.attr;
  61. let parent = this.$parent;
  62. while(!parent.preview || typeof parent.preview !== 'function') {
  63. parent = parent.$parent;
  64. }
  65. parent.removeImageUrl(src);
  66. this.preview = false;
  67. }
  68. // 判断按照那种方式进行缩放
  69. if (originalWidth > windowWidth) {
  70. // 在图片width大于手机屏幕width时候
  71. results.imageWidth = windowWidth;
  72. results.imageheight = windowWidth * (originalHeight / originalWidth);
  73. } else {
  74. // 否则展示原来的数据
  75. results.imageWidth = originalWidth;
  76. results.imageheight = originalHeight;
  77. }
  78. return results;
  79. },
  80. },
  81. };
  82. </script>