VueJavaScriptFrontend
Share:
Vue 3 Composition API Guide
The Composition API in Vue 3 is a revolutionary feature that provides better code organization and logic reuse capabilities. Let's explore how to effectively use this feature.
Why Choose Composition API?
Compared to the Options API, the Composition API offers several advantages:
- Better code organization
- Stronger type inference
- Easier logic reuse
Basic Usage
import { ref, computed, onMounted } from 'vue'
export default {
setup() {
// Reactive state
const count = ref(0)
// Computed property
const doubleCount = computed(() => count.value * 2)
// Methods
const increment = () => {
count.value++
}
// Lifecycle hooks
onMounted(() => {
console.log('Component mounted')
})
// Return for template usage
return {
count,
doubleCount,
increment
}
}
}
Best Practices
- Use composables to extract reusable logic
- Keep setup functions concise
- Use TypeScript for better type support
Real-world Example
Let's look at a practical example: a user list with search and filter functionality.
<script setup>
import { ref, computed } from 'vue'
import { useUsers } from '@/composables/users'
const { users, loading } = useUsers()
const searchQuery = ref('')
const filteredUsers = computed(() => {
return users.value.filter(user =>
user.name.toLowerCase().includes(searchQuery.value.toLowerCase())
)
})
</script>
<template>
<div>
<input v-model="searchQuery" placeholder="Search users...">
<div v-if="loading">Loading...</div>
<ul v-else>
<li v-for="user in filteredUsers" :key="user.id">
{{ user.name }}
</li>
</ul>
</div>
</template>
Conclusion
The Composition API not only provides better code organization but also helps us write more maintainable and reusable code. By properly using composables, we can build clearer and more scalable applications.