calculatingHeight.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. *
  3. * @param parentElement 基准容器Ref
  4. * @param fixedHeight 固定减去的值
  5. * @param elementList 需要减去的可变的容器RefList
  6. * @returns 高度值number
  7. */
  8. export const useCalculatingHeight = (
  9. parentElement: HTMLElement | null,
  10. fixedHeight: number,
  11. elementList: Ref<HTMLElement | null>[]
  12. ) => {
  13. const containerHeight = ref(0)
  14. const calculatingHeight = () => {
  15. if (parentElement) {
  16. containerHeight.value = parentElement.offsetHeight - fixedHeight
  17. elementList.forEach((item: any) => {
  18. if (item.value) {
  19. containerHeight.value -= item.value.offsetHeight || 0
  20. }
  21. })
  22. }
  23. }
  24. // 创建 ResizeObserver 观察变化
  25. const resizeObserver = new ResizeObserver(() => {
  26. calculatingHeight()
  27. })
  28. // 开始观察
  29. const startObserving = () => {
  30. if (parentElement) {
  31. resizeObserver.observe(parentElement)
  32. }
  33. elementList.forEach((item) => {
  34. if (item.value) {
  35. resizeObserver.observe(item.value)
  36. }
  37. })
  38. }
  39. // Vue 生命周期钩子
  40. onMounted(() => {
  41. nextTick(() => {
  42. calculatingHeight()
  43. startObserving()
  44. })
  45. })
  46. // 停止观察
  47. const stopObserving = () => {
  48. resizeObserver.disconnect()
  49. }
  50. // Vue 生命周期钩子
  51. onMounted(() => {
  52. nextTick(() => {
  53. calculatingHeight()
  54. startObserving()
  55. })
  56. })
  57. onBeforeUnmount(() => {
  58. stopObserving()
  59. })
  60. return containerHeight
  61. }