Skip to content
On this page

useElementSize

Category
Last Changed
20 days ago

Reactive size of an HTML element. ResizeObserver MDN

Demo

Resize the box to see changes

Usage

<template>
  <div ref="el">
    Height: {{ height }}
    Width: {{ Width }}
  </div>
</template>

<script>
import { ref } from 'vue'
import { useElementSize } from '@vueuse/core'

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>

<script>
import { ref } from 'vue'
import { useElementSize } from '@vueuse/core'

export default {
  setup() {
    const el = ref(null)
    const { width, height } = useElementSize(el)

    return {
      el,
      width,
      height,
    }
  }
})
</script>

Component

This function also provides a renderless component version via the @vueuse/components package. Learn more about the usage.
<UseElementSize v-slot="{ width, height }">
  Width: {{ width }}
  Height: {{ height }}
</UseElementSize>
<UseElementSize v-slot="{ width, height }">
  Width: {{ width }}
  Height: {{ height }}
</UseElementSize>

Type Declarations

export interface ElementSize {
  width: number
  height: number
}
/**
 * Reactive size of an HTML element.
 *
 * @see https://vueuse.org/useElementSize
 * @param target
 * @param callback
 * @param options
 */
export declare function useElementSize(
  target: MaybeElementRef,
  initialSize?: ElementSize,
  options?: ResizeObserverOptions
): {
  width: Ref<number>
  height: Ref<number>
}
export declare type UseElementSizeReturn = ReturnType<typeof useElementSize>
export interface ElementSize {
  width: number
  height: number
}
/**
 * Reactive size of an HTML element.
 *
 * @see https://vueuse.org/useElementSize
 * @param target
 * @param callback
 * @param options
 */
export declare function useElementSize(
  target: MaybeElementRef,
  initialSize?: ElementSize,
  options?: ResizeObserverOptions
): {
  width: Ref<number>
  height: Ref<number>
}
export declare type UseElementSizeReturn = ReturnType<typeof useElementSize>

Source

SourceDemoDocs

Contributors

Anthony Fu
wheat
webfansplz
Shinigami
Alex Kozack
Sanxiaozhizi

Changelog

v7.6.2 on 2/13/2022
7b400 - fix: should reset value while element unmounted (#1254)
v6.4.0 on 9/17/2021
e557f - feat: added 'as' prop to renderable components (#742)
v4.11.2 on 5/30/2021
68c7d - feat(typedef): add return typedefs (#543) (#544)
v5.0.0-beta.2 on 5/25/2021
5bede - feat: introduce components & directives (#486)
useElementSize has loaded