Blog>
Snippets

Responsive Design with Vue 3 Composition API

Show how to use Vue 3's Composition API to create a responsive design, by setting up reactive breakpoints and adjusting template rendering.
import { ref, computed, onMounted, onUnmounted } from 'vue';

export default {
  setup() {
    const width = ref(window.innerWidth);

    // Update the width ref when the window is resized
    function onResize() {
      width.value = window.innerWidth;
    }

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

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

    // Define breakpoints
    const breakpoints = {
      sm: 640,
      md: 768,
      lg: 1024,
      xl: 1280
    };

    // Compute properties for each breakpoint
    const isSmall = computed(() => width.value < breakpoints.sm);
    const isMedium = computed(() => width.value >= breakpoints.sm && width.value < breakpoints.md);
    const isLarge = computed(() => width.value >= breakpoints.md && width.value < breakpoints.lg);
    const isExtraLarge = computed(() => width.value >= breakpoints.lg);

    // Return reactive properties to use in the template
    return { isSmall, isMedium, isLarge, isExtraLarge };
  }
};
This code snippet sets up a Vue 3 Composition API component that tracks the window width and provides computed properties to determine the current responsive breakpoint. The `onResize` function updates the width when the window is resized. The `onMounted` and `onUnmounted` lifecycle hooks add and remove the resize event listener. Breakpoints are defined, and computed properties (`isSmall`, `isMedium`, `isLarge`, `isExtraLarge`) determine the current screen size based on these breakpoints. These properties can be used within the template to conditionally render content or styles based on the current breakpoint.