Guides

Building Vue Composition API patterns with Vue 3 and Pinia

This guide provides a structured approach to migrating Vue 2 projects to Vue 3 with Composition API, integrating TypeScript, and setting up production-ready tooling. Focuses on actionable steps for enterprise Vue workflows.

2-3 hours6 steps
1

Set up Vue 3 project with Vite

Create a new Vue 3 project using Vite to establish a modern build pipeline. This provides faster development server startup and better TypeScript integration compared to Vue CLI.

setup.sh
npm create vite@latest my-vue3-app -- --template vue
2

Create migration plan

Audit existing Vue 2 components to identify deprecated features (e.g., $dispatch, filters) and create a component-by-component migration checklist. Use vue-migration plugin for automated warnings.

npm install -D vue-migration
npx vue-migration --check
3

Convert Options API to Composition API

Replace data() and methods{} with setup() and reactive/ref() patterns. Use Vue 3's reactivity system to manage component state and lifecycle hooks.

<script>
import { ref, onMounted } from 'vue';
export default {
  setup() {
    const count = ref(0);
    onMounted(() => {
      console.log('Component mounted');
    });
    return { count };
  }
}
</script>

⚠ Common Pitfalls

  • Forgetting to return reactive properties from setup()
  • Incorrectly using this in composition functions
4

Integrate TypeScript

Configure tsconfig.json for Vue 3 and add type definitions for components. Use defineComponent() with explicit prop types and interface-based component definitions.

{
  "compilerOptions": {
    "module": "ESNext",
    "target": "ES2015",
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "skipLibCheck": true
  }
}
5

Setup Pinia for state management

Replace Vuex with Pinia by creating stores with defineStore(). Migrate mutation patterns to actions and ensure proper module organization for large applications.

import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  actions: {
    increment() {
      this.count++;
    }
  }
});
6

Implement testing with Vitest

Configure Vitest for unit testing components and composables. Use Vue Test Utils for shallow rendering and mock dependencies in test cases.

npm install -D vitest
npx vitest init

What you built

This migration workflow establishes a Vue 3 foundation with modern tooling. Verify all components pass tests, ensure type safety, and validate performance with Vue DevTools before deployment.