vue.joedoe.dev

← All the recipesComposablesVue 3.5+

An element's size, live

A ResizeObserver wrapped in a composable, and useTemplateRef to grab the element by name.

TypeScript
import { onMounted, onUnmounted, ref, type Ref } from "vue";

/** The live width and height of an element, with a ResizeObserver. */
export function useElementSize(target: Readonly<Ref<HTMLElement | null>>) {
	const width = ref(0);
	const height = ref(0);
	let observer: ResizeObserver | undefined;

	onMounted(() => {
		if (!target.value) return;
		observer = new ResizeObserver(([entry]) => {
			width.value = Math.round(entry.contentRect.width);
			height.value = Math.round(entry.contentRect.height);
		});
		observer.observe(target.value);
	});
	onUnmounted(() => observer?.disconnect());

	return { width, height };
}

0 × 0

Arrastra la esquina. Con este ancho usaría una columna.

↑↓ move · ↵ open · esc close