Vue 3: Migration and the New Composition API
In 2018, the Vue community is buzzing with the first RFCs for Vue 3. While Vue 2's "Options API" (data, methods, computed, etc.) has served us well, we've started to hit the "organization wall" in larger components. Features are spread across multiple options, and logic reuse via mixins is fraught with naming collisions.
The answer is the Composition API. It's not a replacement for the Options API, but a new way to organize your component's logic.
Why Composition API?
In Vue 2, logic for a single feature is fragmented. With the Composition API, you can keep all the code for a specific feature in one place, even in a separate file.
Practical Example: A Reusable Mouse Tracker
Before the Composition API, we would use a mixin. In 2018, we can use a "composable" function.
// useMouse.js
import { ref, onMounted, onUnmounted } from 'vue';
export function useMouse() {
const x = ref(0);
const y = ref(0);
function update(event) {
x.value = event.pageX;
y.value = event.pageY;
}
onMounted(() => window.addEventListener('mousemove', update));
onUnmounted(() => window.removeEventListener('mousemove', update));
return { x, y };
}
And in your component:
<template>
<div>Mouse position: {{ x }}, {{ y }}</div>
</template>
<script>
import { useMouse } from './useMouse';
export default {
setup() {
const { x, y } = useMouse();
return { x, y };
}
}
</script>
The Power of setup()
The setup() function is the entry point for the Composition API. It runs before the component is created, once the props are resolved. This is where you define all your reactive state, computed properties, and lifecycle hooks.
What about TypeScript?
One of the biggest drivers for Vue 3 in 2018 is better TypeScript support. The Composition API is built from the ground up to work with TypeScript's type inference, making it much easier to write type-safe components than with the Options API.
Vue 3 is still in the works, but the movement toward composition-based architecture is clear. If you're building large Vue apps in 2018, you should start thinking about how to refactor your mixins into composables.