|
| 1 | +# useSize |
| 2 | + |
| 3 | +Vue function that tracks the size of an HTML element. |
| 4 | + |
| 5 | +This function is based on the [ResizeObserver API](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver). |
| 6 | + |
| 7 | +Please note that **ResizeObserver does not work on certain browsers such as IE/Edge/Safari**, |
| 8 | +therefore you should add a polyfill such as: |
| 9 | + |
| 10 | +```js |
| 11 | +import { ResizeObserver } from '@juggle/resize-observer' |
| 12 | +window.ResizeObserver = window.ResizeObserver || ResizeObserver |
| 13 | +``` |
| 14 | + |
| 15 | +## Reference |
| 16 | + |
| 17 | +```typescript |
| 18 | +function useSize( |
| 19 | + elRef: Ref<null | HTMLElement>, |
| 20 | + options?: ResizeObserverObserveOptions, |
| 21 | + runOnMount?: boolean |
| 22 | +): { |
| 23 | + observedEntry: Ref<ResizeObserverEntry | null> |
| 24 | + isTracking: Ref<boolean> |
| 25 | + start: () => void |
| 26 | + stop: () => void |
| 27 | +} |
| 28 | +``` |
| 29 | + |
| 30 | +### Parameters |
| 31 | + |
| 32 | +- `elRef: Ref<null | HTMLElement>` the element to observe for size changes |
| 33 | +- `options: ResizeObserverObserveOptions` the [ResizeObserver options](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver/observe) |
| 34 | +- `runOnMount: boolean` whether to observe the element on mount, `true` by default |
| 35 | + |
| 36 | +### Returns |
| 37 | + |
| 38 | +- `observedEntry: Ref<ResizeObserverEntry | null>` the [observed entry](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry) |
| 39 | +- `isTracking: Ref<boolean>` whether this function observer is running or not |
| 40 | +- `start: Function` the function used for start observing |
| 41 | +- `stop: Function` the function used for stop observing |
| 42 | + |
| 43 | +## Usage |
| 44 | + |
| 45 | +```html |
| 46 | +<template> |
| 47 | + <div class="box" ref="elRef"> |
| 48 | + <div class="box__msg">Resize me!</div> |
| 49 | + <div class="box__info">{{ width }} {{ height }}</div> |
| 50 | + </div> |
| 51 | +</template> |
| 52 | + |
| 53 | +<script lang="ts"> |
| 54 | + import Vue from 'vue' |
| 55 | + import { useSize } from 'vue-use-kit' |
| 56 | + import { ref, watch } from '@src/api' |
| 57 | +
|
| 58 | + export default Vue.extend({ |
| 59 | + name: 'UseSizeDemo', |
| 60 | + setup() { |
| 61 | + const elRef = ref(null) |
| 62 | + const width = ref(0) |
| 63 | + const height = ref(0) |
| 64 | + const { observedEntry } = useSize(elRef) |
| 65 | +
|
| 66 | + watch(observedEntry, () => { |
| 67 | + if (!observedEntry.value) return |
| 68 | + const { width, height } = observedEntry.value.contentRect |
| 69 | + width.value = width |
| 70 | + height.value = height |
| 71 | + }) |
| 72 | + return { elRef, width, height } |
| 73 | + } |
| 74 | + }) |
| 75 | +</script> |
| 76 | + |
| 77 | +<style scoped> |
| 78 | + .box { |
| 79 | + resize: both; |
| 80 | + overflow: auto; |
| 81 | + } |
| 82 | +</style> |
| 83 | +``` |
0 commit comments