# useResizeObserver

useResizeObserver

ResizeObserver (opens new window) lets you know when an element's size changes.

# Example

💡 resize the textarea, and watch the contentRect changed.

# Usage

<div class="wrapper">
  <label for="story">Tell us your story:</label>

  <textarea
    id="story"
    name="story"
    rows="5"
    cols="33"
    ref="textareaRef"
  >
    It was a dark and stormy night...
  </textarea>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
import { useResizeObserver } from '@vueblocks/vue-use-core'

export default {
  setup () {
    const rectState = ref({})
    const textareaRef = ref(null)

    useResizeObserver(
      textareaRef,
      ([entry]) => {
        rectState.value = entry.contentRect
      }
    )

    return {
      textareaRef,
      rectState
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# Typing

/**
 * Size of a specific box.
 *
 * https://drafts.csswg.org/resize-observer-1/#resizeobserversize
 */
interface ResizeObserverSize {
  readonly inlineSize: number;
  readonly blockSize: number;
}
/**
 * Used to observe different box sizes.
 *
 * https://drafts.csswg.org/resize-observer-1/#enumdef-resizeobserverboxoptions
 */
declare enum ResizeObserverBoxOptions {
  BORDER_BOX = "border-box",
  CONTENT_BOX = "content-box",
  DEVICE_PIXEL_CONTENT_BOX = "device-pixel-content-box"
}
/**
 * Options to be given to the resize observer,
 * when observing a new element.
 *
 * https://drafts.csswg.org/resize-observer-1/#dictdef-resizeobserveroptions
 */
interface ResizeObserverOptions {
  box?: 'content-box' | 'border-box' | 'device-pixel-content-box' | ResizeObserverBoxOptions;
}
/**
 * https://drafts.csswg.org/resize-observer-1/#resize-observer-entry-interface
 */
interface ResizeObserverEntry {
  readonly target: Element;
  readonly contentRect: DOMRectReadOnly;
  readonly borderBoxSize?: ReadonlyArray<ResizeObserverSize>;
  readonly contentBoxSize?: ReadonlyArray<ResizeObserverSize>;
  readonly devicePixelContentBoxSize?: ReadonlyArray<ResizeObserverSize>;
}
/**
 * https://drafts.csswg.org/resize-observer-1/#resize-observer-callback
 */
declare type ResizeObserverCallback = (
  entries: ResizeObserverEntry[],
  observer: ResizeObserver
) => void;

/**
 * ResizeObserver immediately detects when an element resizes and provides accurate sizing information back to the callback handler.
 * @param target
 * @param callback
 * @param options
 */
declare const useResizeObserver: (
  target: Element,
  callback: ResizeObserverCallback,
  options: ResizeObserverOptions
) => {
  stop: () => void;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59