javascript / intermediate
Snippet
Encapsulating Logic with Composables
Composables are the primary pattern for reusing stateful logic in Vue. They are functions that leverage the Composition API to encapsulate specific features, returning reactive state and methods that can be easily shared between multiple components.
snippet.js
1
2
3
4
5
6
7
8
import { ref } from 'vue';export function useToggle(initialValue = false) {const status = ref(initialValue);const toggle = () => (status.value = !status.value);return { status, toggle };}
vue
Breakdown
1
export function useToggle
The 'use' prefix is a convention indicating the function is a stateful composable.
2
const status = ref(initialValue);
Internal reactive state that is private to the composable instance.
3
return { status, toggle };
Exposes the state and the updater function to the consuming component.