Introduction
Composables help you reuse code easily in Vue. They keep your code clean and organized by sharing logic across components.
Composables help you reuse code easily in Vue. They keep your code clean and organized by sharing logic across components.
import { ref } from 'vue' export function useCounter() { const count = ref(0) function increment() { count.value++ } return { count, increment } }
import { ref } from 'vue' export function useToggle() { const isOn = ref(false) function toggle() { isOn.value = !isOn.value } return { isOn, toggle } }
import { ref, onMounted, onUnmounted } from 'vue' export function useWindowWidth() { const width = ref(window.innerWidth) function updateWidth() { width.value = window.innerWidth } onMounted(() => { window.addEventListener('resize', updateWidth) }) onUnmounted(() => { window.removeEventListener('resize', updateWidth) }) return { width } }
This Vue component uses the useCounter composable to add a counter button. Clicking the button increases the count.
<script setup> import { useCounter } from './useCounter' const { count, increment } = useCounter() </script> <template> <button @click="increment" aria-label="Increment counter">Count: {{ count }}</button> </template>
Always name composables starting with 'use' to keep your code clear.
Composables help separate logic from UI, making components easier to read and maintain.
Use composables to share logic without copying code between components.
Composables let you reuse logic easily in Vue apps.
They keep your components simple and clean.
Use composables to organize and share code better.
function useToggle() {
const on = ref(false);
function toggle() { on.value = !on.value; }
return { on, toggle };
}on.value after calling toggle() twice starting from initial state?on starts as false.false to true. Second toggle flips true back to false.function useData() {
const data = ref(null);
fetch('api/data').then(response => {
data.value = response.json();
});
return { data };
}Pass the test and this pattern moves unknown