img.vue 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. <template>
  2. <view>
  3. <image
  4. :class="attrs.class"
  5. :lazy-load="true"
  6. :mode="attrs.mode || 'widthFix'"
  7. :src="attrs.src"
  8. :style="attrs.style + ' width:' + size.w + 'px;height:' + size.h + 'px;'"
  9. @load="load"
  10. ></image>
  11. </view>
  12. </template>
  13. <script>
  14. const config = require('../config');
  15. export default {
  16. data() {
  17. return {
  18. attr: {
  19. src: '',
  20. class: '',
  21. style: ''
  22. },
  23. size: {
  24. w: 0,
  25. h: 0
  26. },
  27. styleObj: {},
  28. attrs: {
  29. class: '',
  30. mode: '',
  31. src: '',
  32. style: ''
  33. }
  34. };
  35. },
  36. options: {
  37. styleIsolation: 'shared'
  38. },
  39. props: {
  40. data: {
  41. type: Object,
  42. default: () => ({})
  43. }
  44. },
  45. mounted() {
  46. // 处理小程序 attached 生命周期
  47. this.attached();
  48. },
  49. methods: {
  50. attached: function () {
  51. const that = this;
  52. let dataAttr = this.data.attrs;
  53. // 将图片大小处理到对象中
  54. if (dataAttr.width) {
  55. that.size.w = +dataAttr.width / config.dpr;
  56. }
  57. if (dataAttr.height) {
  58. that.size.h = +dataAttr.height / config.dpr;
  59. }
  60. // 将样式合并到样式对象中
  61. if (dataAttr.style) {
  62. let re = /;\s{0,}/gi;
  63. dataAttr.style = dataAttr.style.replace(re, ';');
  64. dataAttr.style.split(';').forEach((item) => {
  65. let itemArr = item.split(':');
  66. if (/^(width|height)$/i.test(itemArr[0])) {
  67. let num = parseInt(itemArr[1]) || 0;
  68. let key = ''; // itemArr[1] = num / config.dpr + itemArr[1].replace(num,'');
  69. switch (itemArr[0].toLocaleLowerCase()) {
  70. case 'width':
  71. key = 'w';
  72. break;
  73. case 'height':
  74. key = 'h';
  75. break;
  76. }
  77. that.size[key] = num / config.dpr;
  78. } else {
  79. that.styleObj[itemArr[0]] = itemArr[1];
  80. }
  81. });
  82. }
  83. // 设置公式图片
  84. that.setData({
  85. attrs: {
  86. src: dataAttr.src,
  87. class: dataAttr.class,
  88. style: that.setStyle(that.styleObj)
  89. },
  90. size: that.size
  91. });
  92. },
  93. // 设置图片样式
  94. setStyle: function (o) {
  95. let str = ``;
  96. for (let key in o) {
  97. str += `${key}:${o[key]};`;
  98. }
  99. return str;
  100. },
  101. // 图片加载完成设置图片大小
  102. load: function (e) {
  103. const that = this;
  104. if (!that.size.w || !that.size.h) {
  105. that.setData({
  106. size: {
  107. w: e.detail.width / config.dpr,
  108. h: e.detail.height / config.dpr
  109. }
  110. });
  111. }
  112. }
  113. },
  114. created: function () {}
  115. };
  116. </script>
  117. <style></style>