Composition API
The Composition API in Vue.js is a modern approach for organizing and structuring component logic, introduced as an alternative to the traditional Options API. Its primary advantage lies in its ability to modularize logic based on feature or functionality rather than component options, making it particularly useful for large-scale applications where code reuse and maintainability are critical. Composition API allows developers to separate reactive state, computed properties, and side effects in a clear and reusable manner, supporting advanced patterns like OOP principles, algorithmic logic, and complex data structures.
Developers use Composition API within the setup() function, which serves as the entry point for defining component state and behavior. Key tools include ref and reactive for creating reactive data, computed for derived state, and watch for observing changes and performing side effects. By combining these features with composable functions, developers can extract and share logic across multiple components, improving code readability and testability.
In this tutorial, readers will learn how to create reactive data structures, implement event handling, apply algorithmic logic within Vue components, and build maintainable and scalable applications using Composition API. The examples focus on solving real-world problems while adhering to Vue.js best practices, including proper state management, error handling, and optimization techniques. This knowledge provides a solid foundation for integrating Vue.js components into complex software architectures, ensuring both performance and maintainability in production-ready applications.
Basic Example
textimport { createApp, ref, computed } from 'vue'
const App = {
setup() {
// Reactive state
const counter = ref(0)
// Increment function
const increment = () => {
counter.value++
}
// Computed property
const doubleCounter = computed(() => counter.value * 2)
return {
counter,
increment,
doubleCounter
}
},
template: ` <div> <h1>Counter: {{ counter }}</h1> <h2>Double Counter: {{ doubleCounter }}</h2> <button @click="increment">Increase</button> </div>
`
}
createApp(App).mount('#app')
In this basic example, the setup() function serves as the core of Composition API, replacing Options API constructs like data, methods, and computed. The ref function creates a reactive single-value variable counter, which automatically updates the template whenever its value changes. The increment function demonstrates event handling by directly modifying counter.value, adhering to Vue's reactivity system without directly manipulating the DOM.
The computed function creates doubleCounter, a derived reactive property that depends on counter, illustrating reactive computation and dependency tracking. Returning counter, increment, and doubleCounter from setup() makes them accessible in the template, demonstrating how Composition API enables modular and reusable logic. For beginners, understanding the .value property for ref variables and the role of the setup return object is crucial. This pattern ensures scalable, testable, and maintainable code that can easily integrate into larger applications or be extracted into reusable composable functions.
Practical Example
textimport { createApp, reactive, watch } from 'vue'
const App = {
setup() {
// Reactive object state
const state = reactive({
tasks: [],
newTask: ''
})
// Add a task
const addTask = () => {
if (state.newTask.trim() !== '') {
state.tasks.push({ text: state.newTask, done: false })
state.newTask = ''
}
}
// Watch for task length changes
watch(() => state.tasks.length, (newLength, oldLength) => {
console.log(`Task count changed from ${oldLength} to ${newLength}`)
})
// Remove a task
const removeTask = (index) => {
state.tasks.splice(index, 1)
}
return {
state,
addTask,
removeTask
}
},
template: ` <div> <h1>Task List</h1> <input v-model="state.newTask" placeholder="Enter a new task" /> <button @click="addTask">Add</button> <ul> <li v-for="(task, index) in state.tasks" :key="index">
{{ task.text }} <button @click="removeTask(index)">Remove</button> </li> </ul> </div>
`
}
createApp(App).mount('#app')
This example also illustrates the application of OOP principles by encapsulating state and operations within a single logical entity. Composition API facilitates modularity, making it easy to extract task management logic into a reusable composable function. Best practices include proper handling of reactive objects, avoiding direct DOM manipulation, and ensuring cleanup of watchers to prevent memory leaks. The example showcases efficient state management, optimized performance, and adherence to Vue.js development conventions for scalable, production-ready applications.
When using Composition API, several Vue.js best practices and common pitfalls must be considered. Proper use of ref and reactive is essential: ref for single values, reactive for objects or arrays. Avoid creating computed properties or watchers dynamically inside render loops to prevent memory leaks and performance degradation.
📊 Reference Table
| Vue.js Element/Concept | Description | Usage Example |
|---|---|---|
| ref | Create a reactive single-value variable | const count = ref(0) |
| reactive | Create a reactive object containing multiple properties | const state = reactive({ name: '', age: 0 }) |
| computed | Create a reactive computed property derived from other reactive data | const double = computed(() => count.value * 2) |
| watch | Observe reactive data changes and execute side effects | watch(() => state.tasks.length, (newVal) => console.log(newVal)) |
| setup | Entry point for defining component state and logic in Composition API | setup() { const data = ref(0); return { data } } |
Key takeaways from learning Composition API include understanding how to manage reactive state, use computed properties and watchers effectively, and modularize logic for maintainable, scalable applications. Composition API allows developers to create highly reusable components, improve code clarity, and integrate advanced algorithms and OOP principles within Vue.js applications.
Next steps include exploring composable functions for logic reuse across components, integrating state management libraries like Pinia for global state, and learning advanced patterns such as async setup and suspense. Practicing these concepts in real projects will reinforce understanding, improve performance, and ensure robust and maintainable applications. Reference official Vue documentation, tutorials, and open-source projects for continued learning and practical application of Composition API techniques.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top