Composables pattern
A composable is a function that uses Composition API features to package reusable stateful logic.
In this page:
Syntax
import { ref } from 'vue';
export function useName() {
const state = ref(initial_value);
function update() { state.value++; }
return { state, update };
}
const { state, update } = useName();
Composables pattern
By convention composables start with use, such as useCounter or useMouse. They create refs, computed values and watchers inside and return them.
Any component can call the composable, getting its own independent state, which replaces mixins with clearer, explicit reuse.
Note:
Return refs from composables so callers can destructure them safely.
Example: Composables pattern
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<counter-a></counter-a>
<counter-b></counter-b>
</div>
<script>
function useCounter(start = 0) {
const count = Vue.ref(start);
const increment = () => count.value++;
const doubled = Vue.computed(() => count.value * 2);
return { count, increment, doubled };
}
const app = Vue.createApp({});
app.component("counter-a", { setup: () => useCounter(0), template: '<button @click="increment">A: {{ count }} ({{ doubled }})</button>' });
app.component("counter-b", { setup: () => useCounter(100), template: '<button @click="increment">B: {{ count }} ({{ doubled }})</button>' });
app.mount("#app");
document.querySelector("button").click();
Vue.nextTick(() => console.log([...document.querySelectorAll("button")].map((b) => b.textContent).join(" | ")));
</script>
</body>
</html>
<!-- Output:
Rendered: A: 1 (2)B: 100 (200)
console: A: 1 (2) | B: 100 (200)
-->
Live Example
Related Topics
Common Mistakes
- Sharing state accidentally through module-level refs
- Forgetting the use prefix
- Returning plain values instead of refs
Chapter Summary
- Composables are use-functions
- They return refs and functions
- Each caller gets its own state
- They replace mixins
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: