useElementSize
获取 HTML 元素的响应式大小。ResizeObserver MDN
Demo
调整框大小以查看更改
用法
vue
<script>
import { useElementSize } from '@vueuse/core'
import { ref } from 'vue'
export default {
setup() {
const el = ref(null)
const { width, height } = useElementSize(el)
return {
el,
width,
height,
}
}
}
</script>
<template>
<div ref="el">
Height: {{ height }}
Width: {{ width }}
</div>
</template>
组件用法
vue
<template>
<UseElementSize v-slot="{ width, height }">
Width: {{ width }} Height: {{ height }}
</UseElementSize>
</template>
指令用法
vue
<script setup lang="ts">
import { vElementSize } from '@vueuse/components'
function onResize({ width, height }: { width: number, height: number }) {
console.log(width, height)
}
</script>
<template>
<textarea v-element-size="onResize" />
<!-- 使用选项 -->
<textarea
v-element-size="[onResize, { width: 100, height: 100 }, { box: 'content-box' }]"
/>
</template>
类型声明
typescript
export interface ElementSize {
width: number
height: number
}
/**
* HTML 元素的响应式尺寸。
*
* @see https://vueuse.org/useElementSize
*/
export declare function useElementSize(
target: MaybeComputedElementRef,
initialSize?: ElementSize,
options?: UseResizeObserverOptions,
): {
width: Ref<number, number>
height: Ref<number, number>
stop: () => void
}
export type UseElementSizeReturn = ReturnType<typeof useElementSize>
Source
贡献者
Anthony Fu
丶远方
webfansplz
Anthony Fu
Mikhailov Nikita
wheat
siaikin
menghan
仿生狮子
ByMykel
jing
vaakian X
Vasily Kuzin
vaakian X
Jelf
Shinigami
Alex Kozack
Sanxiaozhizi