Vue 2 to Vue 3: Options to Composition, Vuex to Pinia
A staged migration off a dead Vue 2 branch without stopping feature work: what actually breaks, the reactivity gotcha that replaces the old one, and the component library problem nobody plans for.
Vue 2 reached end of life. The job we get asked to do is never "migrate to Vue 3" in isolation - it is "migrate to Vue 3 while we keep shipping features", which is a different and more constrained problem. Here is the sequence we use, and the two places it reliably goes wrong.
What actually breaks
Bootstrapping. new Vue({ ... }).$mount('#app') becomes createApp(App).mount('#app'), and every global - Vue.use, Vue.component, Vue.mixin, Vue.prototype.$thing - becomes a call on the app instance.
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
import router from './router';
import BaseButton from './components/BaseButton.vue';
const app = createApp(App);
app.use(router);
app.use(createPinia());
app.component('BaseButton', BaseButton);
app.config.globalProperties.$formatPrice = (n) => n.toFixed(2);
app.mount('#app');
Filters are gone. {{ price | currency }} no longer parses; replace with a method or computed. Most codebases have five filters used in two hundred places, so this is find-and-replace with an eye on pipe characters inside string literals.
v-model on components changed. The value/input pair became modelValue/update:modelValue, and the .sync modifier is gone in favour of v-model:arg. So a child that declared a value prop and emitted input now declares modelValue and emits update:modelValue, and a parent that had :title.sync="t" writes v-model:title="t" against a child that declares a title prop and emits update:title.
$listeners merged into $attrs. A wrapper that did v-on="$listeners" now needs only v-bind="$attrs", which already carries them.
Fragments. A component may now have multiple root nodes - so code reading this.$el to measure or position something gets a text node or the first of several, and attribute inheritance silently stops when there is more than one root. Budget time here if your design system positions tooltips.
$children is gone with no replacement; use refs, provide/inject, or an explicit contract. Functional SFCs (functional: true) are gone too - convert them to normal components.
The event bus. new Vue() used as a global emitter has no Vue 3 equivalent and no drop-in. Every usage becomes props and emits, provide/inject, or a store - design work rather than a port. The bus usually sets the timeline on these projects, so audit it before promising a date.
The reactivity gotcha that replaces the old one
Vue 2's reactivity was built on Object.defineProperty, which could not see properties added after creation or array assignment by index. Hence Vue.set. Vue 3 uses a Proxy, so both are fixed - and a new trap replaces them, one that catches anyone assuming the upgrade removed the whole class of problem: destructuring a reactive() object loses reactivity.
Nobody really believes this until they watch it happen, so here is a twenty-line stand-in for Vue's reactivity, small enough to read in one sitting and real enough to reproduce the bug:
let activeEffect = null;
const deps = new Map();
function track(key) {
if (!activeEffect) return;
if (!deps.has(key)) deps.set(key, new Set());
deps.get(key).add(activeEffect);
}
function trigger(key) {
(deps.get(key) || new Set()).forEach((fn) => fn());
}
function reactive(obj) {
return new Proxy(obj, {
get(t, k, r) { track(k); return Reflect.get(t, k, r); },
set(t, k, v, r) { const ok = Reflect.set(t, k, v, r); trigger(k); return ok; },
});
}
function ref(value) {
return { get value() { track('value'); return value; },
set value(v) { value = v; trigger('value'); } };
}
function watchEffect(fn) { activeEffect = fn; fn(); activeEffect = null; }
const state = reactive({ count: 0 });
const boxed = ref(0);
// WRONG: destructuring reads the value once and hands you a copy.
const { count } = state;
watchEffect(() => console.log('destructured count ->', count));
// RIGHT: read inside the effect, so the proxy can track it.
watchEffect(() => console.log('state.count ->', state.count));
watchEffect(() => console.log('boxed.value ->', boxed.value));
console.log('--- mutate ---');
state.count = 1;
boxed.value = 1;
Under Node that prints:
destructured count -> 0
state.count -> 0
boxed.value -> 0
--- mutate ---
state.count -> 1
boxed.value -> 1
The destructured effect never runs again: no error, no warning, a value frozen at the moment you destructured it. The reason is visible in the proxy: tracking happens in the get trap, so a read outside an effect registers nothing, and a plain const binding has no trap at all. A ref survives because the value lives behind an accessor: every .value read is a fresh, trackable read. That is the whole reason for .value, and for toRefs(), which turns each property of a reactive object into one of those boxes so destructuring stays live.
Options to Composition, side by side
The mapping is mostly boring: data becomes ref, methods become plain functions, watch gains an explicit source, lifecycle hooks gain an on prefix. The Options version:
export default {
props: {
productId: { type: Number, required: true },
threshold: { type: Number, default: 0 },
},
data() {
return { offers: [], loading: false };
},
computed: {
cheapest() {
return this.offers.length ? Math.min(...this.offers.map((o) => o.price)) : null;
},
},
watch: {
productId: { immediate: true, handler(id) { this.fetchOffers(id); } },
},
methods: {
async fetchOffers(id) {
this.loading = true;
try {
this.offers = await (await fetch(`/api/products/${id}/offers`)).json();
if (this.cheapest !== null && this.cheapest <= this.threshold) {
this.$emit('alert', this.cheapest);
}
} finally {
this.loading = false;
}
},
reload() { this.fetchOffers(this.productId); },
},
mounted() { window.addEventListener('focus', this.reload); },
beforeDestroy() { window.removeEventListener('focus', this.reload); },
};
And the same component as <script setup>:
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue';
const props = defineProps({
productId: { type: Number, required: true },
threshold: { type: Number, default: 0 },
});
const emit = defineEmits(['alert']);
const offers = ref([]);
const loading = ref(false);
const cheapest = computed(() =>
offers.value.length ? Math.min(...offers.value.map((o) => o.price)) : null);
async function fetchOffers(id) {
loading.value = true;
try {
offers.value = await (await fetch(`/api/products/${id}/offers`)).json();
if (cheapest.value !== null && cheapest.value <= props.threshold) {
emit('alert', cheapest.value);
}
} finally {
loading.value = false;
}
}
function reload() { fetchOffers(props.productId); }
watch(() => props.productId, fetchOffers, { immediate: true });
onMounted(() => window.addEventListener('focus', reload));
onBeforeUnmount(() => window.removeEventListener('focus', reload));
Two things worth noticing. The watch source is a getter - () => props.productId, not props.productId - for exactly the reason the harness demonstrates: passing the value passes a snapshot. And beforeDestroy is now onBeforeUnmount; a listener never torn down is the kind of leak that shows up after an hour of use.
Vuex to Pinia
The conversion deletes a concept rather than renaming one: mutations disappear. Actions mutate state directly, getters are computed, and the module wrapper goes because every store is already its own namespace. A Vuex module like this:
export default {
namespaced: true,
state: () => ({ items: [], loading: false }),
getters: {
total: (state) => state.items.reduce((sum, i) => sum + i.price * i.qty, 0),
},
mutations: {
SET_LOADING(state, value) { state.loading = value; },
SET_ITEMS(state, items) { state.items = items; },
},
actions: {
async load({ commit }, cartId) {
commit('SET_LOADING', true);
try {
const res = await fetch(`/api/carts/${cartId}`);
commit('SET_ITEMS', await res.json());
} finally {
commit('SET_LOADING', false);
}
},
},
};
becomes, in options style - the closest shape to what you had, so the one we use for a first pass:
import { defineStore } from 'pinia';
export const useCartStore = defineStore('cart', {
state: () => ({ items: [], loading: false }),
getters: {
total: (state) => state.items.reduce((sum, i) => sum + i.price * i.qty, 0),
},
actions: {
async load(cartId) {
this.loading = true;
try {
const res = await fetch(`/api/carts/${cartId}`);
this.items = await res.json();
} finally {
this.loading = false;
}
},
},
});
Or in setup style, with Composition API primitives:
import { ref, computed } from 'vue';
import { defineStore } from 'pinia';
export const useCartStore = defineStore('cart', () => {
const items = ref([]);
const loading = ref(false);
const total = computed(() => items.value.reduce((sum, i) => sum + i.price * i.qty, 0));
async function load(cartId) {
loading.value = true;
try {
const res = await fetch(`/api/carts/${cartId}`);
items.value = await res.json();
} finally {
loading.value = false;
}
}
return { items, loading, total, load };
});
Consuming it is where the earlier lesson pays off. A store instance is a reactive object, so destructuring its state and getters breaks reactivity for the reason the Proxy harness showed; storeToRefs() converts them to refs first. Actions are bound functions and destructure safely.
import { onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import { useCartStore } from '@/stores/cart';
const cart = useCartStore();
// Actions come off the store directly; they are bound.
const { load } = cart;
// State and getters must go through storeToRefs, or they stop updating.
const { items, total, loading } = storeToRefs(cart);
onMounted(() => load(props.cartId));
The staging plan
The order matters more than any individual conversion, because the app must be shippable at the end of every day.
- Build tooling first, still on Vue 2. Move off vue-cli to Vite while the framework is unchanged, so you debug one thing at a time.
- Switch to the migration build. Alias
vueto@vue/compatin your bundler config withMODE: 2. The app now runs on Vue 3 internals while still being Vue-2-shaped, and the console lists every incompatibility as a warning. That warning list is your real backlog - not a guess. - Clear warnings by class, turning compat flags off one at a time.
FILTERS: falsewhen the last filter is gone,COMPONENT_V_MODEL: falsewhen the last child is converted. A flag turned off is a class of bug that cannot come back in a new commit - that is what stops feature work undoing the migration. - Convert components to
<script setup>opportunistically. The Options API still works in Vue 3, so convert a component when you are already editing it. - Move stores last. Vuex and Pinia coexist in one app, so migrate one store per pull request.
// main.js - step 3, flipping classes off as you finish them
import { configureCompat } from 'vue';
configureCompat({
MODE: 3,
FILTERS: false,
COMPONENT_V_MODEL: false,
INSTANCE_LISTENERS: 'suppress-warning',
GLOBAL_MOUNT: 'suppress-warning',
});
Step 2 is where most migrations stall, and not because of Vue. It stalls on a component library that never shipped a Vue 3 version - an admin UI kit, a table component, a date picker somebody chose in 2019. The compat build does not help, because the library ships Vue 2 render functions. The honest options are three: replace it, usually the largest single line in the estimate because every screen it touches needs re-testing; fork it, viable only for a small library and you own it forever; or postpone until that dependency is off the critical path. We have recommended all three. What we will not do is start without pricing that dependency, because discovering it in week three turns a planned project into an open-ended one. It is the first thing we look at on a Vue upgrade engagement, alongside how the front end talks to the backend application - an API reshape and a framework migration in the same quarter is one change too many.
When not to do this
If the front end is a handful of sprinkled-in Vue 2 widgets on a server-rendered Laravel or Django page rather than a single-page app, Vue 3 may be the wrong target entirely. Rewriting those widgets as plain JavaScript removes a framework dependency instead of updating one, and is often less work than the compat dance. And if the application is feature-frozen and internal-only, the security calculus differs from a server-side one: the code runs in the user's browser, not on your infrastructure. Not a reason to leave it forever, but a reason it can wait behind things that actually bleed.
If you want a realistic sequence and a dependency audit before committing budget to a Vue 2 migration, send us the package.json: that file answers most of the estimating questions on its own. Start a project and include it.
We ship and run our own products. We build yours the same way.
Start a project