Vue 3’s Composition API provides better code organization. Here’s how to use it effectively.
Setup
import { ref, computed, watch } from 'vue';
export default {
setup() {
const count = ref(0);
const doubled = computed(() => count.value * 2);
watch(count, (newVal) => {
console.log('Count changed:', newVal);
});
return { count, doubled };
}
}
Script Setup
<script setup>
import { ref, computed } from 'vue';
const count = ref(0);
const doubled = computed(() => count.value * 2);
function increment() {
count.value++;
}
</script>
Composables
// useCounter.js
import { ref } from 'vue';
export function useCounter(initialValue = 0) {
const count = ref(initialValue);
const increment = () => count.value++;
const decrement = () => count.value--;
return { count, increment, decrement };
}
Best Practices
- Use composables for reusability
- Keep setup functions focused
- Use script setup syntax
- Organize by feature
- Extract complex logic
Conclusion
Vue 3 Composition API enables better code organization! 🎯