use-content-height.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { computed, onMounted, ref, watch } from 'vue';
  2. import { CSS_VARIABLE_LAYOUT_CONTENT_HEIGHT } from '@vben-core/constants';
  3. import { getElementVisibleHeight } from '@vben-core/toolkit';
  4. import { useCssVar, useDebounceFn, useWindowSize } from '@vueuse/core';
  5. /**
  6. * @zh_CN 获取内容高度(可视区域,不包含滚动条)
  7. */
  8. function useContentHeight() {
  9. const contentHeight = useCssVar(CSS_VARIABLE_LAYOUT_CONTENT_HEIGHT);
  10. const contentStyles = computed(() => {
  11. return {
  12. height: `var(${CSS_VARIABLE_LAYOUT_CONTENT_HEIGHT})`,
  13. };
  14. });
  15. return { contentHeight, contentStyles };
  16. }
  17. /**
  18. * @zh_CN 创建内容高度监听
  19. */
  20. function useContentHeightListener() {
  21. const contentElement = ref<HTMLDivElement | null>(null);
  22. const { height, width } = useWindowSize();
  23. const contentHeight = useCssVar(CSS_VARIABLE_LAYOUT_CONTENT_HEIGHT);
  24. const debouncedCalcHeight = useDebounceFn(() => {
  25. contentHeight.value = `${getElementVisibleHeight(contentElement.value)}px`;
  26. }, 200);
  27. watch([height, width], () => {
  28. debouncedCalcHeight();
  29. });
  30. onMounted(() => {
  31. debouncedCalcHeight();
  32. });
  33. return { contentElement };
  34. }
  35. export { useContentHeight, useContentHeightListener };