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

  1. Use composables for reusability
  2. Keep setup functions focused
  3. Use script setup syntax
  4. Organize by feature
  5. Extract complex logic

Conclusion

Vue 3 Composition API enables better code organization! 🎯