Skip to main content
InterviewHubPRO
Section Overview
Q14

Question 14 of 50

Part 2: Core Architecture & Implementation (Mid-Level)

28%
Vue.js & Composition API (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)

How do you structure Composables in Vue 3?

senior LevelCode ExampleSystem DesignVue & Nuxt

In Simple Words: A Composable is a function that leverages Vue's Composition API to encapsulate and share stateful logic:

typescript
// composables/useMouse.ts
import { ref, onMounted, onUnmounted } from 'vue';

export function useMouse() {
  const x = ref(0);
  const y = ref(0);

  function update(event: MouseEvent) {
    x.value = event.pageX;
    y.value = event.pageY;
  }

  onMounted(() => window.addEventListener('mousemove', update));
  onUnmounted(() => window.removeEventListener('mousemove', update));

  return { x, y };
}

Best Practice Rules: Name begins with use, returns a plain object of refs, cleans up side-effects in onUnmounted.