Skip to content

监听元素宽高

相关方法

说明

useListenHeightWidth 用于实时监听 DOM 元素的宽高变化。

它利用 ResizeObserver API 来观察元素的大小,并返回一个响应式的对象包含当前的宽度和高度。

支持传入 CSS 选择器字符串或 Vue 的 Ref 对象作为监听目标。同时支持自动减去指定的高度或宽度,方便计算剩余空间。

类型定义

typescript
function useListenHeightWidth(
  domSelector: string | Ref<Element>,
  deleteHeight: number = 0,
  deleteWidth: number = 0,
): { height: number; width: number };

参数说明

参数类型默认值说明
domSelectorstring | Ref<Element>-监听元素的选择器字符串或 Vue Ref 对象
deleteHeightnumber0计算返回高度时需要减去的数值
deleteWidthnumber0计算返回宽度时需要减去的数值

代码示例

基础用法

typescript
import { useListenHeightWidth } from '@vue3-simple-bui/platform';
import { ref } from 'vue';

// 方式一:传入选择器字符串
const size1 = useListenHeightWidth('#container-id'); 

// 方式二:传入 Ref 对象
const containerRef = ref<HTMLElement>();
const size2 = useListenHeightWidth(containerRef); 

减去指定宽高

适用于需要计算剩余高度的场景,例如表格高度自适应。

typescript
import { useListenHeightWidth } from '@vue3-simple-bui/platform';

// 监听元素,并自动减去 100px 的高度和 20px 的宽度
const contentSize = useListenHeightWidth('#content', 100, 20); 

// contentSize.height 已经是减去 100 后的值

基于 MIT 许可发布