Welcome to HowToShipIt — practical how-to guides for developers: code, AI tools, and servers, explained step by step.

Vue 3 Composition API Migration: Options API to script setup, Step by Step (2026)

Still running your Vue app on the Options API? You’re not behind — Vue 3 supports both API styles, and the official docs present them side by side. But the ecosystem has quietly settled: most new libraries, job postings, and tutorials now assume the Composition API, and every Vue 3 Composition API migration story ends the same way — developers who feared the rewrite finished their first component in an hour and never looked back. This guide shows you how to convert your components piece by piece, from data() to ref() to <script setup>, without breaking anything along the way.

Written and verified October 2026 against the official Vue.js documentation.

Should You Even Migrate? A Quick Decision Guide

Not every codebase needs a migration. Here’s an honest decision framework before you touch any code:

  • Migrate if: your components share duplicated logic across mixins, your data() and methods have grown past 200 lines, or you’re starting new features in an existing app.
  • Migrate gradually if: you’re on a stable, working app with simple components. New components in Composition API, old ones when you next touch them.
  • Don’t migrate if: your app is stable, simple, and rarely changes. The Options API is not deprecated and isn’t going anywhere.

The critical fact that makes this safe: both APIs coexist in the same codebase and even in the same project. You can convert one component at a time while the rest keep working. The migration build isn’t required — this is a pure refactor, not a version upgrade.

The Vue 3 Composition API Migration Map

Before touching code, memorise this mapping. Almost every migration is a mechanical application of it:

Options API Composition API (<script setup>)
data() { return { x: 0 } } const x = ref(0) or reactive({...})
computed: { double() {...} } const double = computed(() => ...)
methods: { save() {...} } function save() {...}
watch: { x(v) {...} } watch(x, (v) => {...})
mounted() {...} onMounted(() => {...})
props: { title: String } const props = defineProps({...})
this.$emit('save') const emit = defineEmits([...])
mixins: [myMixin] Extract to a useMyThing() composable
this.$refs.input const input = ref(null) + ref="input"

Step-by-Step: Options API to Composition API

1. Set up <script setup> first

<script setup> is compile-time syntactic sugar for the Composition API: top-level bindings you declare in the script are automatically available in the template, with no export default or setup() boilerplate. Start by swapping the script block of the component you’re converting and leave the template and styles untouched:

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

// everything below is automatically exposed to the template
</script>

2. data() becomes ref() and reactive()

Convert each data() property individually. The rule of thumb: ref() for primitives (and anything you might reassign wholesale), reactive() for objects you only mutate. In the template, refs unwrap automatically — {{ count }} still works — but in JavaScript you must use .value.

// BEFORE
export default {
  data() {
    return {
      count: 0,
      user: { name: 'Ada', role: 'admin' }
    }
  }
}

// AFTER
<script setup>
import { ref, reactive } from 'vue'

const count = ref(0)
const user = reactive({ name: 'Ada', role: 'admin' })
</script>

One subtle trap: replacing a reactive() object breaks reactivity, because the proxy reference changes. user = {...} (reassignment) loses reactivity; mutating it (user.name = 'Grace') is fine. If you need to swap an object wholesale, use a ref() instead.

3. methods: become plain functions

Drop the methods object and the this keyword. Functions declared at the top level of <script setup> are directly usable in the template:

// BEFORE
methods: {
  increment() {
    this.count++
  },
  reset() {
    this.count = 0
    this.user.name = 'Ada'
  }
}

// AFTER
function increment() {
  count.value++
}

function reset() {
  count.value = 0
  user.name = 'Ada'
}

Delete this everywhere as you go. If a method still reaches for this.$something, you’re looking at a global property (like this.$route or this.$store) — that’s a separate migration step covered below.

4. computed: becomes computed()

Wrap each computed getter in computed(() => ...). Getters read with .value inside other functions, but the template still uses the bare name:

// BEFORE
computed: {
  displayName() {
    return `${this.user.name} (${this.user.role})`
  },
  isAdmin() {
    return this.user.role === 'admin'
  }
}

// AFTER
import { computed } from 'vue'

const displayName = computed(() => `${user.name} (${user.role})`)
const isAdmin = computed(() => user.role === 'admin')

5. watch: becomes watch() or watchEffect()

The watch option’s modifiers map directly to options on the watch() function: deep: true and immediate: true stay exactly as they were.

// BEFORE
watch: {
  userId(newId, oldId) {
    this.fetchUser(newId)
  },
  'user.name': {
    handler(v) { console.log('name changed:', v) },
    immediate: true
  }
}

// AFTER
import { watch } from 'vue'

watch(userId, (newId, oldId) => {
  fetchUser(newId)
})

watch(() => user.name, (v) => {
  console.log('name changed:', v)
}, { immediate: true })

Note the arrow-function wrapper when watching a nested property of a reactive() object: watch(() => user.name, ...). Pass user directly and the watcher fires on any change to the whole object — and since the source is the object itself, newValue and oldValue will be the same reference.

For cases where you just need “re-run this whenever any dependency changes” (the old pattern of a watcher with immediate: true calling a method), watchEffect() is shorter — it tracks whatever you read inside it automatically.

6. Lifecycle hooks become onX() functions

Import the hooks you need from vue. The names map 1:1: mounted → onMounted, unmounted → onUnmounted, updated → onUpdated, beforeMount → onBeforeMount, and so on. The one exception: there are no beforeCreate/created equivalents, because the body of <script setup> itself runs during component creation.

// BEFORE
mounted() {
  window.addEventListener('resize', this.handleResize)
},
unmounted() {
  window.removeEventListener('resize', this.handleResize)
}

// AFTER
import { onMounted, onUnmounted } from 'vue'

onMounted(() => {
  window.addEventListener('resize', handleResize)
})
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

Registering setup and teardown side by side like this is one of the migration’s biggest readability wins — the pair that used to live in two distant options now sits in one block.

7. props and $emit become defineProps and defineEmits

defineProps and defineEmits are compiler macros — you don’t import them, they’re available automatically inside <script setup>:

// BEFORE
export default {
  props: {
    userId: { type: String, required: true }
  },
  emits: ['select'],
  methods: {
    choose(id) {
      this.$emit('select', id)
    }
  }
}

// AFTER
<script setup>
const props = defineProps({
  userId: { type: String, required: true }
})
const emit = defineEmits(['select'])

function choose(id) {
  emit('select', id)
}
</script>

One gotcha: props are one-way — never mutate them. If the old component did this.someProp = x (which Vue always warned against), the migration forces you to fix it properly: emit an event and let the parent own the state, or create a local ref seeded from the prop. Also, don’t destructure props into plain variables unless you’re on Vue 3.5 or later — on older versions, destructuring snapshots the values and silently loses reactivity.

8. Two-way v-model components get defineModel()

If your component implements v-model with a modelValue prop plus an update:modelValue emit, Vue 3.4’s defineModel() macro collapses all of that into one line returning a writable ref:

// BEFORE (Options API v-model pattern)
export default {
  props: ['modelValue'],
  emits: ['update:modelValue'],
  methods: {
    onInput(e) {
      this.$emit('update:modelValue', e.target.value)
    }
  }
}

// AFTER
<script setup>
const model = defineModel()
</script>

<template>
  <input v-model="model" />
</template>

defineModel() also accepts a name (defineModel('firstName')) for components with multiple v-models, plus default and required options. If you must support Vue versions below 3.4, stick with the manual modelValue + update:modelValue pattern — defineModel doesn’t exist there.

9. this.$refs becomes a template ref

// BEFORE
export default {
  methods: {
    focusSearch() {
      this.$refs.searchInput.focus()
    }
  }
}

// AFTER
<script setup>
import { ref } from 'vue'

const searchInput = ref(null)

function focusSearch() {
  searchInput.value.focus()
}
</script>

<template>
  <input ref="searchInput" />
</template>

Declare a ref with the same name as the template ref attribute and Vue wires them together. (Vue 3.5+ also offers useTemplateRef(), a dedicated API for this that avoids the name-matching convention.)

A Complete Before-and-After: Migrating a Real Component

Theory is nice; here’s the full thing. A UserCard component that fetches a user by prop, filters their posts, and emits an event — first in the Options API, then migrated:

<!-- BEFORE: Options API -->
<template>
  <div v-if="loading">Loading...</div>
  <div v-else-if="error">{{ error }}</div>
  <div v-else>
    <h2>{{ displayName }}</h2>
    <input ref="searchInput" v-model="query" placeholder="Filter posts" />
    <ul>
      <li v-for="post in filteredPosts" :key="post.id">{{ post.title }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  props: { userId: { type: String, required: true } },
  emits: ['loaded'],
  data() {
    return { user: null, query: '', loading: true, error: null }
  },
  computed: {
    displayName() {
      return this.user ? `${this.user.name} (@${this.user.username})` : ''
    },
    filteredPosts() {
      if (!this.user) return []
      const q = this.query.toLowerCase()
      return this.user.posts.filter(p => p.title.toLowerCase().includes(q))
    }
  },
  watch: {
    userId(newId) { this.fetchUser(newId) }
  },
  mounted() {
    this.fetchUser(this.userId)
  },
  methods: {
    async fetchUser(id) {
      this.loading = true
      this.error = null
      try {
        const res = await fetch(`/api/users/${id}`)
        if (!res.ok) throw new Error(`HTTP ${res.status}`)
        this.user = await res.json()
        this.$emit('loaded', this.user)
      } catch (e) {
        this.error = e.message
      } finally {
        this.loading = false
      }
    }
  }
}
</script>
<!-- AFTER: Composition API with <script setup> -->
<template>
  <div v-if="loading">Loading...</div>
  <div v-else-if="error">{{ error }}</div>
  <div v-else>
    <h2>{{ displayName }}</h2>
    <input ref="searchInput" v-model="query" placeholder="Filter posts" />
    <ul>
      <li v-for="post in filteredPosts" :key="post.id">{{ post.title }}</li>
    </ul>
  </div>
</template>

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

const props = defineProps({
  userId: { type: String, required: true }
})
const emit = defineEmits(['loaded'])

const user = ref(null)
const query = ref('')
const loading = ref(true)
const error = ref(null)
const searchInput = ref(null)

const displayName = computed(() =>
  user.value ? `${user.value.name} (@${user.value.username})` : ''
)

const filteredPosts = computed(() => {
  if (!user.value) return []
  const q = query.value.toLowerCase()
  return user.value.posts.filter(p => p.title.toLowerCase().includes(q))
})

async function fetchUser(id) {
  loading.value = true
  error.value = null
  try {
    const res = await fetch(`/api/users/${id}`)
    if (!res.ok) throw new Error(`HTTP ${res.status}`)
    user.value = await res.json()
    emit('loaded', user.value)
  } catch (e) {
    error.value = e.message
  } finally {
    loading.value = false
  }
}

watch(() => props.userId, fetchUser)
onMounted(() => fetchUser(props.userId))
</script>

Same template, same behaviour. The logic that was scattered across data, computed, watch, mounted, and methods now reads top to bottom as one coherent story.

Replace Mixins With Composables

Mixins still work in Vue 3’s Options API, but they don’t fit the Composition API at all — and they’re the number-one reason teams migrate. A mixin’s magic property merging (unclear where this.page came from, name collisions, implicit dependencies) disappears when you rewrite it as a plain function:

// BEFORE: mixins/pagination.js
export default {
  data() {
    return { page: 1, perPage: 10 }
  },
  computed: {
    paginatedItems() {
      const start = (this.page - 1) * this.perPage
      return this.items.slice(start, start + this.perPage)
    },
    totalPages() {
      return Math.ceil(this.items.length / this.perPage)
    }
  }
}

// AFTER: composables/usePagination.js
import { ref, computed } from 'vue'

export function usePagination(items, perPage = 10) {
  const page = ref(1)

  const paginatedItems = computed(() => {
    const list = items.value ?? items
    const start = (page.value - 1) * perPage
    return list.slice(start, start + perPage)
  })

  const totalPages = computed(() => {
    const list = items.value ?? items
    return Math.ceil(list.length / perPage)
  })

  function nextPage() {
    if (page.value < totalPages.value) page.value++
  }

  return { page, paginatedItems, totalPages, nextPage }
}

Usage in a component is explicit — you see exactly what’s imported and where it comes from:

<script setup>
import { usePagination } from './composables/usePagination'

const props = defineProps({ items: { type: Array, required: true } })
const { page, paginatedItems, totalPages, nextPage } = usePagination(props.items)
</script>

Name composables useXxx, accept refs or plain values as inputs, and always clean up listeners/timers inside onUnmounted (or via the composable’s own hooks). Extract one mixin, use it in two components, and you’ve already paid back the effort.

7 Migration Gotchas (and How to Avoid Them)

  1. Forgetting .value. The most common bug by far. Refs unwrap in templates but not in plain JS. Linters like eslint-plugin-vue catch most of these — turn it on.
  2. Mixing this with setup state. In <script setup> there is no this at all. If you keep a component’s Options API options alongside a setup() function, this in the options can’t see unreturned setup bindings — convert the whole component at once instead of half-migrating.
  3. Destructuring props on Vue < 3.5. const { userId } = defineProps(...) loses reactivity on older versions. Access via props.userId or upgrade to Vue 3.5+.
  4. Replacing a reactive() object. Assigning a new object to a reactive variable breaks the proxy. Use ref() for anything you replace wholesale.
  5. Watching the wrong source. watch(user, ...) watches the whole object (new and old values are the same reference); watch(() => user.name, ...) watches one field. Pick deliberately.
  6. Forgetting to return from setup(). Only applies if you use the long-form setup() instead of <script setup> — everything must be returned to reach the template. This alone is a reason to prefer <script setup>.
  7. Global properties (this.$route, this.$store). These have Composition API equivalents: useRoute() / useRouter() from vue-router, useStore() from Pinia/Vuex. Hunt down every this.$ reference before you finish a component.

The Post-Migration Checklist

Run through this before you mark a component done:

  • Run your unit tests (Vitest/Vue Test Utils work the same — only the component internals changed).
  • Click through the component manually: initial render, loading states, error states, and the prop-change path your watcher covers.
  • Check the console for warnings: undeclared emits, mutating props, and ref name mismatches all show up there.
  • Remove the old mixin file only when no component imports it anymore — grep first.
  • If you use TypeScript, prefer type-based declarations: defineProps<{ userId: string }>() and defineEmits<{ loaded: [user: User] }>() give you full type checking without the runtime object.

You don’t need to migrate your whole app this weekend. Convert the components you touch, extract the mixins that hurt, and let the codebase drift toward Composition API one pull request at a time. The mapping is mechanical, the pitfalls are known, and the payoff — logic that reads in order instead of scattered across five option blocks — shows up on the very first component.

Further Reading & References

Leave a Comment