vue.joedoe.dev

← Totes les receptesComposablesVue 3.5+

La mida d'un element, en viu

Un ResizeObserver embolcallat en un composable i useTemplateRef per agafar l'element pel seu nom.

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.

↑↓ moure's · ↵ obrir · esc tancar