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
Single-File Component
Define a Vue 3 component with script setup, template, and scoped styles.
Composition API
Organize reactive state, computed, and lifecycle logic by feature.
Refs & Reactive
Choose between ref and reactive for reactive state.
Computed & Watch
Derive values with computed and react to changes with watch.
Props & Emits
Declare inputs and events, and implement v-model on a component.
Lifecycle Hooks
Register lifecycle callbacks as composable functions.