The Composition API is a new feature introduced in Vue 3 that provides an alternative syntax for writing component logic. It aims to address the limitations of the Options API, especially when dealing with large components or code reuse. The Composition API allows you to organize and reuse code more effectively.
Key Concepts
- Setup Function
The setup
function is the entry point of the Composition API. It is called before the component is created and serves as a place to define reactive state, lifecycle hooks, and other logic.
<script> import { ref } from 'vue'; export default { setup() { const count = ref(0); function increment() { count.value++; } return { count, increment }; } }; </script>
- Reactive State
Reactive state can be created using ref
and reactive
functions.
- ref: Creates a reactive reference to a primitive value.
- reactive: Creates a reactive object.
import { ref, reactive } from 'vue'; export default { setup() { const count = ref(0); const state = reactive({ name: 'Vue.js', version: 3 }); return { count, state }; } };
- Computed Properties
Computed properties can be created using the computed
function.
import { ref, computed } from 'vue'; export default { setup() { const count = ref(0); const doubleCount = computed(() => count.value * 2); return { count, doubleCount }; } };
- Watchers
Watchers can be created using the watch
function to perform side effects in response to reactive state changes.
import { ref, watch } from 'vue'; export default { setup() { const count = ref(0); watch(count, (newValue, oldValue) => { console.log(`Count changed from ${oldValue} to ${newValue}`); }); return { count }; } };
- Lifecycle Hooks
Lifecycle hooks can be used within the setup
function using their respective functions.
import { onMounted, onUnmounted } from 'vue'; export default { setup() { onMounted(() => { console.log('Component mounted'); }); onUnmounted(() => { console.log('Component unmounted'); }); return {}; } };
Practical Example
Let's create a simple counter component using the Composition API.
<template> <div> <p>Count: {{ count }}</p> <button @click="increment">Increment</button> </div> </template> <script> import { ref } from 'vue'; export default { setup() { const count = ref(0); function increment() { count.value++; } return { count, increment }; } }; </script>
Explanation
- Template: Displays the count and a button to increment it.
- Setup Function: Initializes the
count
state usingref
and defines theincrement
function. - Return Object: Exposes
count
andincrement
to the template.
Exercise
Create a Vue component using the Composition API that:
- Has a reactive state for a list of items.
- Allows adding a new item to the list.
- Displays the list of items.
Solution
<template> <div> <input v-model="newItem" placeholder="Add a new item" /> <button @click="addItem">Add Item</button> <ul> <li v-for="item in items" :key="item">{{ item }}</li> </ul> </div> </template> <script> import { ref } from 'vue'; export default { setup() { const items = ref([]); const newItem = ref(''); function addItem() { if (newItem.value.trim()) { items.value.push(newItem.value); newItem.value = ''; } } return { items, newItem, addItem }; } }; </script>
Explanation
- Template: Includes an input field for the new item, a button to add the item, and a list to display the items.
- Setup Function: Initializes
items
andnewItem
usingref
, and defines theaddItem
function. - Return Object: Exposes
items
,newItem
, andaddItem
to the template.
Conclusion
The Composition API in Vue 3 provides a flexible and powerful way to organize and reuse component logic. By using the setup
function, reactive state, computed properties, watchers, and lifecycle hooks, you can create more maintainable and scalable Vue applications. This new API is especially useful for large components and complex logic, making your code cleaner and easier to understand.
Vue.js Course
Module 1: Introduction to Vue.js
- What is Vue.js?
- Setting Up the Development Environment
- Creating Your First Vue Application
- Understanding the Vue Instance
Module 2: Vue.js Basics
- Template Syntax
- Data Binding
- Computed Properties and Watchers
- Class and Style Bindings
- Conditional Rendering
- List Rendering
Module 3: Vue.js Components
- Introduction to Components
- Props and Custom Events
- Slots
- Dynamic and Async Components
- Component Communication
Module 4: Vue Router
Module 5: State Management with Vuex
- Introduction to Vuex
- State, Getters, Mutations, and Actions
- Modules in Vuex
- Using Vuex in Components
- Advanced Vuex Patterns
Module 6: Vue.js Directives
Module 7: Vue.js Plugins
Module 8: Testing in Vue.js
Module 9: Advanced Vue.js Concepts
- Render Functions and JSX
- Server-Side Rendering (SSR) with Nuxt.js
- Vue 3 Composition API
- Performance Optimization