Vue Composition API
The Composition API is a set of APIs that allows us to author Vue components using imported functions instead of declaring options. It's an umbrella term that covers:
- Reactivity API (ref, reactive, computed, watch)
- Lifecycle hooks (onMounted, onUnmounted, etc.)
- Dependency injection (provide, inject)
Why Composition API?
The Composition API addresses several limitations of the Options API:
- Better logic reuse - Extract and reuse stateful logic easily
- More flexible code organization - Group code by feature, not by option type
- Better type inference - TypeScript support is much better
- Smaller bundle size - Tree-shakeable, unlike Options API
<script setup>
The <script setup> syntax is a compile-time syntactic sugar for using Composition API inside Single File Components (SFCs). It's the recommended syntax because:
<!-- With <script setup> -->
<script setup>
const count = ref(0)
function increment() {
count.value++
}
</script>
vs.
<!-- Without <script setup> -->
<script>
import { ref } from 'vue'
export default {
setup() {
const count = ref(0)
function increment() {
count.value++
}
return { count, increment }
}
}
</script>
Composables
Composables are functions that leverage Vue's Composition API to encapsulate and reuse stateful logic. They typically start with "use" (like useCounter, useMouse).
Here's a simple composable example:
// composables/useCounter.js
export function useCounter(initialValue = 0) {
const count = ref(initialValue)
function increment() {
count.value++
}
function decrement() {
count.value--
}
return { count, increment, decrement }
}
Then use it in your component:
<script setup>
const { count, increment, decrement } = useCounter(10)
</script>
Challenge
Create a reusable composable for a toggle functionality:
- Create a composable function called
useTogglethat accepts an initial boolean value - The composable should return:
value: A ref holding the current statetoggle: A function to toggle the statesetTrue: A function to set state to truesetFalse: A function to set state to false
- Use the composable in the component to show/hide content
Tip: Composables are just functions! They can use any Composition API features like ref, computed, watch, etc.
If you get stuck, you can check the solution by clicking the button below.
The Composition API gives you powerful tools for organizing and reusing logic. Next, we'll dive deeper into components!