index.vue 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <template>
  2. <view class="hc-img-view"
  3. :style="{
  4. 'background-image': srcs,
  5. 'width': widths,
  6. 'height': heights,
  7. 'aspect-ratio': aspectRatio
  8. }"></view>
  9. </template>
  10. <script setup>
  11. import {onMounted, ref, watch} from "vue";
  12. const props = defineProps({
  13. 'src': String,
  14. 'width': [String, Number],
  15. 'height': [String, Number]
  16. });
  17. //初始变量
  18. const srcs = ref('');
  19. const widths = ref('');
  20. const heights = ref('');
  21. const aspectRatio = ref('');
  22. //加载完成
  23. onMounted(() => {
  24. setStyleData(props.src, props.width, props.height);
  25. });
  26. //监听变化
  27. watch(() => [
  28. props.src,
  29. props.width,
  30. props.height
  31. ], ([src, width, height]) => {
  32. setStyleData(src, width, height);
  33. })
  34. //设置样式
  35. const setStyleData = (src, width, height) => {
  36. srcs.value = 'url(' + src + ')';
  37. widths.value = (width * 2) + 'rpx';
  38. heights.value = (height * 2) + 'rpx';
  39. aspectRatio.value = 'auto ' + width + ' / ' + height;
  40. }
  41. </script>
  42. <style lang="scss" scoped>
  43. .hc-img-view {
  44. background-position: 0% 0%;
  45. background-size: 100% 100%;
  46. display: inline-block;
  47. }
  48. </style>