cwg-match-media.vue 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <template>
  2. <!-- #ifdef H5 -->
  3. <view>
  4. <match-media v-bind="mediaAttrs">
  5. <slot />
  6. </match-media>
  7. </view>
  8. <!-- #endif -->
  9. <!-- #ifdef APP-PLUS -->
  10. <view v-if="shouldShow">
  11. <slot />
  12. </view>
  13. <!-- #endif -->
  14. </template>
  15. <script setup lang="ts">
  16. import { ref, computed, onMounted, onUnmounted } from 'vue';
  17. const props = defineProps({
  18. minWidth: {
  19. type: Number,
  20. default: undefined
  21. },
  22. maxWidth: {
  23. type: Number,
  24. default: undefined
  25. }
  26. })
  27. const shouldShow = ref(true)
  28. const mediaAttrs = computed(() => {
  29. const attrs: Record<string, number> = {};
  30. if (props.minWidth !== undefined) attrs['min-width'] = props.minWidth;
  31. if (props.maxWidth !== undefined) attrs['max-width'] = props.maxWidth;
  32. return attrs;
  33. })
  34. function checkWidth() {
  35. const width = uni.getSystemInfoSync().windowWidth
  36. shouldShow.value = (props.minWidth === undefined || width >= props.minWidth) && (props.maxWidth === undefined || width <= props.maxWidth)
  37. }
  38. // #ifdef APP-PLUS
  39. checkWidth()
  40. let resizeListener: any
  41. onMounted(() => {
  42. resizeListener = () => checkWidth()
  43. uni.onWindowResize && uni.onWindowResize(resizeListener)
  44. })
  45. onUnmounted(() => {
  46. uni.offWindowResize && uni.offWindowResize(resizeListener)
  47. })
  48. // #endif
  49. </script>
  50. <style lang="scss" scoped>
  51. @import "@/uni.scss";
  52. </style>