Skip to content

useElementSize

Category
Export Size
897 B
Last Changed
7 months ago

Reactive size of an HTML element. ResizeObserver MDN

Demo

Resize the box to see changes

Usage

vue
<script setup lang="ts">
import { 
useElementSize
} from '@vueuse/core'
import {
useTemplateRef
} from 'vue'
const
el
=
useTemplateRef
('el')
const {
width
,
height
} =
useElementSize
(
el
)
</script> <template> <
div
ref
="
el
">
Height: {{
height
}}
Width: {{
width
}}
</
div
>
</template>

Component Usage

This function also provides a renderless component version via the @vueuse/components package. Learn more about the usage.

vue
<template>
  <UseElementSize v-slot="{ 
width
,
height
}">
Width: {{
width
}} Height: {{
height
}}
</UseElementSize> </template>

Directive Usage

This function also provides a directive version via the @vueuse/components package. Learn more about the usage.

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-si
ze="
onResize
" />
<!-- with options --> <
textarea
v-element-si
ze="
[
onResize
, {
width
: 100,
height
: 100 }, {
box
: 'content-box' }]
" />
</template>

Type Declarations

ts
export interface ElementSize {
  
width
: number
height
: number
} /** * Reactive size of an HTML element. * * @see https://vueuse.org/useElementSize */ export declare function
useElementSize
(
target
:
MaybeComputedElementRef
,
initialSize
?: ElementSize,
options
?:
UseResizeObserverOptions
,
): {
width
:
ShallowRef
<number, number>
height
:
ShallowRef
<number, number>
stop
: () => void
} export type
UseElementSizeReturn
=
ReturnType
<typeof
useElementSize
>

Source

SourceDemoDocs

Contributors

Anthony Fu
Anthony Fu
webfansplz
IlyaL
menghan
Mikhailov Nikita
wheat
青椒肉丝
Robin
James Garbutt
IlyaL
我想静静
siaikin
仿生狮子
ByMykel
jing
vaakian X
Vasily Kuzin
vaakian X
Jelf
Shinigami
Alex Kozack
Sanxiaozhizi

Changelog

v14.0.0-alpha.0 on
8c521 - feat(components)!: refactor components and make them consistent (#4912)
v13.2.0 on
9889f - fix: component type warning (#4722)
v12.3.0 on
021d0 - feat(toArray): new utility function (#4432)
v12.0.0-beta.1 on
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
v10.10.0 on
d8015 - fix: use getBoundingClientRect get element size on SVG (#3940)
v10.6.0 on
165c8 - fix: get value in onMounted hook (#3366)
5f545 - feat: stop function (#3367)
v10.4.0 on
791f7 - fix: add as prop for component usage (#3274)

Released under the MIT License.

Join the Biggest FREE AI-Driven Development Event for Vue Developers
Save My Seat