Skip to content

useElementSize

Category
Export Size
955 B
Last Changed
15 minutes ago

获取 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

SourceDemoDocs

贡献者

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

变更日志

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.