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 };
}<script setup lang="ts">
import { computed, useTemplateRef } from "vue";
import { useElementSize } from "./useElementSize";
/* Vue 3.5: useTemplateRef by name, instead of a ref with the same name as the attribute. */
const box = useTemplateRef<HTMLElement>("box");
const { width, height } = useElementSize(box);
const layout = computed(() => (width.value < 260 ? "una columna" : "dos columnas"));
</script>
<template>
<div ref="box" class="box">
<p>
<strong>{{ width }} × {{ height }}</strong>
</p>
<p class="muted">Arrastra la esquina. Con este ancho usaría {{ layout }}.</p>
</div>
</template>
<style scoped>
.box {
resize: both;
overflow: auto;
width: 70%;
min-width: 8rem;
max-width: 100%;
min-height: 6rem;
padding: 0.75rem;
border: 2px dashed #42b883;
border-radius: 10px;
}
.box p {
margin: 0 0 0.25rem;
}
</style>0 × 0
Arrastra la esquina. Con este ancho usaría una columna.