Skip to content
Vue 3

Composables

Extract reusable reactive logic into a useMouse composable.

By EZ4Code Team
composablesreuse

Code

import { ref, onMounted, onUnmounted } from "vue";

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

  function update(e) {
    x.value = e.clientX;
    y.value = e.clientY;
  }

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

  return { x, y };
}

// Usage in any component:
// const { x, y } = useMouse();

Explanation

Composables are reusable functions that encapsulate reactive state and lifecycle logic. They follow the useX naming convention and return refs and methods. This pattern replaces mixins and enables clean, typed logic sharing across components.

More Vue 3 Snippets