useWindowWidth()?import { ref, onMounted, onUnmounted } from 'vue'; export function useWindowWidth() { const width = ref(window.innerWidth); function updateWidth() { width.value = window.innerWidth; } onMounted(() => { window.addEventListener('resize', updateWidth); }); onUnmounted(() => { window.removeEventListener('resize', updateWidth); }); return { width }; }
ref returns and how the event listeners affect it.The composable returns an object with a reactive width property. This property updates automatically when the window is resized because of the event listener.
count.value after calling useCounter() and incrementing twice?count.value after calling increment() twice?import { ref } from 'vue'; export function useCounter() { const count = ref(0); function increment() { count.value++; } return { count, increment }; } // Usage example: const { count, increment } = useCounter(); increment(); increment();
count is a ref and increments by 1 each time increment() is called.The count starts at 0 and increments by 1 each time increment() is called. After two calls, it becomes 2.
isActive and a function toggle to flip its value..value to access or update refs.Option A correctly uses ref and updates isActive.value. Option A returns a non-reactive primitive. Option A uses a plain variable, not reactive. Option A tries to toggle the ref itself, not its value.
<template> <button @click="toggle">Toggle</button> <p>{{ isActive }}</p> </template> <script setup> import { ref } from 'vue'; const isActive = ref(false); function toggle() { isActive.value = !isActive.value; } </script>
The toggle function tries to assign a boolean directly to the ref variable isActive, which breaks reactivity. It should update isActive.value instead.
Custom composables let you share reactive logic easily between components, improving code reuse and clarity.
