← Back to all snippets
JAVASCRIPT

Create Reusable Logic with Vue 3 Composables (useWindowSize)

Discover how to build and use composables in Vue 3's Composition API to encapsulate and reuse reactive stateful logic, like tracking window dimensions across components.

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

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

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

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

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

  return { width, height };
}

// MyComponent.vue
<template>
  <div>
    <h1>Window Size Tracker</h1>
    <p>Width: {{ windowSize.width }}px</p>
    <p>Height: {{ windowSize.height }}px</p>
  </div>
</template>

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

const windowSize = useWindowSize();
</script>
How it works: This snippet illustrates creating a reusable 'composable' function, `useWindowSize`, using Vue 3's Composition API. This composable encapsulates the logic for tracking the browser window's dimensions reactively. It uses `ref` to hold reactive width and height, `onMounted` to add a 'resize' event listener, and `onUnmounted` to clean up. Any component can then import and use `useWindowSize` to get current window dimensions without duplicating logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs