Vue 3 Composition API Preview: The Future of Vue

Vue 3 is coming later this year, and the Composition API is its most significant feature. Having played with the preview, here’s what I’ve learned.

Code on screen
Photo by Christopher Gower on Unsplash

Why Composition API?

The Options API (data, methods, computed) works great for small components. But as components grow, related logic gets scattered. Composition API lets you organize by feature, not option type.

Basic Example

<script>
import { ref, computed, onMounted } from 'vue';

export default {
  setup() {
    // Reactive state
    const count = ref(0);
    
    // Computed
    const doubled = computed(() => count.value * 2);
    
    // Methods
    function increment() {
      count.value++;
    }
    
    // Lifecycle
    onMounted(() => {
      console.log('Component mounted');
    });
    
    // Expose to template
    return { count, doubled, increment };
  }
};
</script>

Composable Functions

// composables/useMouse.js
import { ref, onMounted, onUnmounted } from 'vue';

export function useMouse() {
  const x = ref(0);
  const y = ref(0);

  function update(e) {
    x.value = e.pageX;
    y.value = e.pageY;
  }

  onMounted(() => window.addEventListener('mousemove', update));
  onUnmounted(() => window.removeEventListener('mousemove', update));

  return { x, y };
}

// Usage in component
const { x, y } = useMouse();

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.