Composition functions (commonly called Vue Composables) are functions that leverage Vue's Composition API to encapsulate, manage, and reuse stateful logic across components.
Composables are Vue's architectural equivalent to React Custom Hooks. By convention, their names start with use....
### Practical Composable Example:
// composables/useWindowSize.ts
import { ref, onMounted, onUnmounted } from 'vue';
export function useWindowSize() {
const width = ref(window.innerWidth);
const height = ref(window.innerHeight);
function update() {
width.value = window.innerWidth;
height.value = window.innerHeight;
}
onMounted(() => window.addEventListener('resize', update));
onUnmounted(() => window.removeEventListener('resize', update));
return { width, height };
}
### Using It in Any Component:
<script setup>
import { useWindowSize } from '@/composables/useWindowSize';
const { width, height } = useWindowSize();
</script>
<template>
<p>Viewport: {{ width }} x {{ height }}</p>
</template>
### Advantages over Mixins:
- Explicit Data Sources: You see exactly where every reactive variable originated.
- No Namespace Collisions: Destructured properties can be renamed easily (
const { width: screenWidth } = useWindowSize()). - Full TypeScript Support: Provides end-to-end type inference.