Reusing Composition API Logic and Working with Reactivity
🎯 Introduction
By the end of this article, you will be able to split complex Vue 3 Composition API logic into reusable modules, making components clearer and easier to maintain. You will extract logic into composables, share values with provide/inject, encapsulate reactive modules, avoid common reactivity pitfalls, and learn techniques that support effective debugging. These skills improve productivity and code quality in both personal and team projects.
🌀 Why Extract Composition API Logic?
In Vue 2, mixins are commonly used to reuse logic, but they can cause naming conflicts and make code harder to follow. Vue 3's Composition API encourages extracting logic into independent functions called composables, making code more modular, readable, and reusable. Let's explore these techniques step by step.
🧩 Extracting Logic into Composables (Custom Hooks)
In Vue 3, a composable is an ordinary function that encapsulates reactive state, computed properties, and methods. It separates logic from components so that it is easier to reuse and test.
export function useCounter() {
const count = ref(0);
function increment() {
count.value++;
}
return { count, increment };
}
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { useCounter } from './useCounter.js';
const { count, increment } = useCounter();
</script>
Here, the counter logic lives in useCounter. A component simply destructures the returned reactive state and methods. Multiple components can reuse this function without duplicating code.
Combining Multiple Composables
A component often calls multiple composables. Their bindings remain explicit and independent, making this approach safer than mixins.
const { count, increment } = useCounter();
const { user, login } = useUser();
🧑🤝🧑 Using provide and inject with the Composition API
Vue's provide and inject support communication across component levels and can also share state within reusable logic. They work with the Composition API using concise syntax.
<template>
<Children />
</template>
<script setup>
import { provide, ref } from 'vue';
import Children from './Children.vue';
const theme = ref('dark');
provide('theme', theme);
</script>
<template>
<div>Current theme: {{ theme }}</div>
</template>
<script setup>
import { inject } from 'vue';
const theme = inject('theme');
</script>
With the Composition API, reactive values shared through provide and inject retain their reactivity. A reactive object accessed by a descendant through inject continues to update reactively.
provide and inject are useful for sharing state between ancestors and descendants or across complex component trees, avoiding the need to pass props through every level.Encapsulating provide and inject in Composables
You can also wrap provide and inject in composables to reuse this logic:
import { provide, inject, ref } from 'vue';
export function provideTheme() {
const theme = ref('light');
provide('theme', theme);
return theme;
}
export function useTheme() {
const theme = inject('theme');
if (!theme) throw new Error('useTheme must be used within the scope of provideTheme');
return theme;
}
The parent calls provideTheme and descendants call useTheme, keeping shared state explicit and the structure clear.
🔄 Encapsulating and Reusing Reactive Modules
Vue 3's reactivity system is based on Proxy. When encapsulating reactive modules, preserve reactive references and avoid losing reactivity through destructuring.
Encapsulating Reactive Form State
For example, a login form can be extracted into a reactive form module:
import { reactive, computed } from 'vue';
export function useLoginForm() {
const form = reactive({
username: '',
password: '',
});
const isValid = computed(() => {
return form.username.length > 0 && form.password.length > 0;
});
function reset() {
form.username = '';
form.password = '';
}
return { form, isValid, reset };
}
Use it in a component:
<template>
<form @submit.prevent="submit">
<input v-model="form.username" placeholder="Username" />
<input type="password" v-model="form.password" placeholder="Password" />
<button :disabled="!isValid">Log in</button>
</form>
</template>
<script setup>
import { useLoginForm } from './useLoginForm';
const { form, isValid, reset } = useLoginForm();
function submit() {
alert(`Username: ${form.username}, password: ${form.password}`);
reset();
}
</script>
Avoiding Reactivity Pitfalls
- Avoid destructuring reactive objects directly. For example, after
const { username } = form,usernameis no longer reactive. Access the reactive object directly or usetoRefs.
import { reactive, toRefs } from 'vue';
const form = reactive({ username: 'Zhang San' });
// Incorrect
const { username } = form;
// Correct
const { username } = toRefs(form);
- Modify arrays and objects through their reactive references. Replacing a reactive object directly breaks its reactive connection.
❓ Questions and Answers
Q1: What is a composable?
A composable is an ordinary function that encapsulates reactive state and logic for reuse and separation of concerns, similar to React Hooks.
Q2: Why avoid destructuring a reactive object directly?
Destructuring can lose reactivity. Use toRefs to turn properties into reactive refs instead.
Q3: How is reactivity preserved with provide/inject?
Reactive values passed through provide remain reactive when retrieved with inject, so updates are reflected automatically.
🧪 Exercises
Exercise 1
Write a useTodoList composable that supports adding, removing, and marking tasks as complete. Use it in a component to manage a todo list.
<template>
<div>
<input v-model="newTodo" placeholder="New task" />
<button @click="addTodo">Add</button>
<ul>
<li v-for="(todo, index) in todos" :key="index">
<label>
<input type="checkbox" v-model="todo.done" />
<span :style="{ textDecoration: todo.done ? 'line-through' : 'none' }">{{
todo.text
}}</span>
</label>
<button @click="removeTodo(index)">Remove</button>
</li>
</ul>
</div>
</template>
<script setup>
// Import and use useTodoList here
</script>
Exercise 2
Create a theme-switching composable. Have the parent provide the current theme through provide, and let a descendant use inject to display and switch the theme.
🎉 You now know how to extract Vue 3 Composition API logic, use provide/inject, encapsulate reactive modules, and recognize the reactivity issues involved in debugging!
