JAVASCRIPT

Create a Reusable Vue 3 Composable for Window Size

Develop a custom Vue 3 composable (`useWindowSize`) to efficiently track and react to real-time changes in the browser window's dimensions across your application, aiding responsive design.

// composables/useWindowSize.js
import { ref, onMounted, onUnmounted } from 'vue';

export function useWindowSize() {
  const width = ref(window.innerWidth);
  const height = ref(window.innerHeight);

  const updateSize = () => {
    width.value = window.innerWidth;
    height.value = window.innerHeight;
  };

  onMounted(() => {
    window.addEventListener('resize', updateSize);
  });

  onUnmounted(() => {
    window.removeEventListener('resize', updateSize);
  });

  return { width, height };
}

// MyResponsiveComponent.vue
<template>
  <div class="responsive-box">
    <h1>Window Size Tracker</h1>
    <p>Width: {{ width }}px</p>
    <p>Height: {{ height }}px</p>
    <p>You are on a {{ isLargeScreen ? 'Large' : 'Small' }} screen.</p>
  </div>
</template>

<script setup>
import { computed } from 'vue';
import { useWindowSize } from './composables/useWindowSize';

const { width, height } = useWindowSize();

const isLargeScreen = computed(() => width.value >= 768);
</script>

<style>
.responsive-box {
  padding: 20px;
  border: 2px solid #42b983;
  text-align: center;
  background-color: #e6ffe6;
  margin: 20px;
  border-radius: 8px;
}
</style>
How it works: This snippet demonstrates creating a reusable Vue 3 composable named `useWindowSize`. This composable utilizes `ref` to hold reactive `width` and `height` values of the browser window. It leverages Vue's lifecycle hooks `onMounted` to add an event listener for the `resize` event and `onUnmounted` to clean up the listener, preventing memory leaks. By returning the reactive `width` and `height`, any component that uses `useWindowSize()` can easily access and react to changes in the window dimensions, making it ideal for implementing responsive UI logic.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs