Skip to content

useElementSize

Category
Export Size
955 B
Last Changed
last month

Reactive size of an HTML element. ResizeObserver MDN

Demo

Resize the box to see changes

Usage

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>

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

Type Declarations

typescript
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: Ref<number, number>
  height: Ref<number, number>
  stop: () => void
}
export type UseElementSizeReturn = ReturnType<typeof useElementSize>

Source

SourceDemoDocs

Contributors

Anthony Fu
webfansplz
Anthony Fu
Mikhailov Nikita
wheat
siaikin
menghan
仿生狮子
ByMykel
jing
vaakian X
Vasily Kuzin
vaakian X
Jelf
Shinigami
Alex Kozack
Sanxiaozhizi

Changelog

v12.0.0-beta.1 on 11/21/2024
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
v10.10.0 on 5/27/2024
d8015 - fix: use getBoundingClientRect get element size on SVG (#3940)
v10.6.0 on 11/9/2023
165c8 - fix: get value in onMounted hook (#3366)
5f545 - feat: stop function (#3367)
v10.4.0 on 8/25/2023
791f7 - fix: add as prop for component usage (#3274)
v9.12.0 on 1/29/2023
902b3 - fix: fix incorrect element size on SVG (#2661)
30475 - fix: use contentBoxSize as an array in useElementSize (#2520)
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)

Released under the MIT License.