JAVASCRIPT
Building a Responsive useWindowSize Composable in Vue 3
Create a custom reusable composable in Vue 3 to track real-time window dimensions, enabling responsive UI logic throughout your application.
// composables/useWindowSize.js
import { ref, onMounted, onUnmounted } from 'vue';
export function useWindowSize() {
const width = ref(window.innerWidth);
const height = ref(window.innerHeight);
const updateWindowSize = () => {
width.value = window.innerWidth;
height.value = window.innerHeight;
};
onMounted(() => {
window.addEventListener('resize', updateWindowSize);
});
onUnmounted(() => {
window.removeEventListener('resize', updateWindowSize);
});
return { width, height };
}
// App.vue (Example Usage)
<template>
<div>
<h1>Window Size Tracker</h1>
<p>Width: {{ width }}px</p>
<p>Height: {{ height }}px</p>
<p v-if="width < 768">This is a small screen device.</p>
<p v-else-if="width >= 768 && width < 1024">This is a medium screen device.</p>
<p v-else>This is a large screen device.</p>
</div>
</template>
<script>
import { useWindowSize } from './composables/useWindowSize.js';
export default {
setup() {
const { width, height } = useWindowSize();
return {
width,
height
};
}
};
</script>
How it works: This snippet defines `useWindowSize`, a custom composable function in Vue 3. Composables encapsulate reactive stateful logic that can be reused across multiple components. `useWindowSize` tracks the browser window's `width` and `height` using reactive `ref`s. It utilizes `onMounted` to add an event listener for `resize` events and `onUnmounted` to clean up the listener, preventing memory leaks. Any component importing and using `useWindowSize()` will get reactive `width` and `height` values, automatically updating when the window is resized, making it perfect for building responsive layouts or adapting UI based on screen dimensions.