Vue.js 2 to 3 Migration: Preparing Your Codebase

Vue 3 is on the horizon (currently in alpha). The biggest change is the **Composition API**, which solves the code organization issues of the Options API in large components. This guide prepares your Vue 2 codebase for the eventual migration.

Options API vs Composition API

graph TD
    subgraph OptionsAPI
        Data[data()]
        Computed[computed]
        Methods[methods]
        Mounted[mounted]
    end
    
    subgraph CompositionAPI
        Setup[setup()]
        Ref[ref / reactive]
        OnMounted[onMounted]
    end
    
    Data --> Setup
    Computed --> Setup
    Methods --> Setup
    Mounted --> Setup
    
    style CompositionAPI fill:#E1F5FE,stroke:#0277BD

The ‘setup’ Method

Instead of scattering logic across data, methods, and lifecycle hooks, everything groups by feature in setup().

import { ref, onMounted } from '@vue/composition-api';

export default {
  setup() {
    // State
    const count = ref(0);
    
    // Method
    const increment = () => count.value++;
    
    // Lifecycle
    onMounted(() => console.log('Mounted!'));
    
    // Expose to template
    return { count, increment };
  }
}

Changes to Global Mounting

In Vue 2, we used new Vue(). In Vue 3, we use createApp() to avoid mutating the global Vue instance.

// Vue 2
import Vue from 'vue';
Vue.use(Router);
new Vue({ render: h => h(App) }).$mount('#app');

// Vue 3
import { createApp } from 'vue';
const app = createApp(App);
app.use(Router);
app.mount('#app');

Key Takeaways

  • Install @vue/composition-api plugin in Vue 2 today to start using the new syntax.
  • Refactor huge components using Composition API to group logical concerns.
  • Avoid mixins; Composition functions (composables) are the replacement.

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.