Skip to content

useElementSize

HTML 元素的反应式大小。调整大小观察者 MDN

¥Reactive size of an HTML element. ResizeObserver MDN

示例

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

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

指令用法

¥Directive 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>

类型声明

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>

源代码

源代码示例文档

变更日志

No recent changes

VueUse 中文网 - 粤ICP备13048890号