Skip to content

Instantly share code, notes, and snippets.

@megakevin
Created October 8, 2026 23:04
Show Gist options
  • Select an option

  • Save megakevin/ba3df673013f555242c66f0c34ffdb83 to your computer and use it in GitHub Desktop.

Select an option

Save megakevin/ba3df673013f555242c66f0c34ffdb83 to your computer and use it in GitHub Desktop.
Guide for a Vue 2 to 3 migration.

Frontend Migration Guide (Vue 2 → Vue 3)

This document is the playbook for finishing the migration of the storefront frontend from Rails 5 + Vue 2 + Webpacker to Rails 8 + Vue 3 + Vite.

It is intentionally specific to this codebase. It is not a general Vue 2 → Vue 3 upgrade guide; for framework-level changes (reactivity, global API, v-model semantics, etc.) consult the official Vue 3 migration guide. This document only captures the decisions, conventions, and translation rules that are unique to this project.

How to use this guide

  • The new code lives in app/frontend/. It already contains a working proof-of-concept slice (the app shell, layout, router, Pinia store, and a few Spraypaint models). Treat it as the reference implementation. When in doubt, match the patterns already established there.
  • The old code lives in old_codebase/app/javascript/ for reference only. It is never imported, built, or run. It is the source material you translate from.
  • Each rule below is phrased as an instruction. When migrating a file, find the rule(s) that apply and follow them. If you discover a new convention or decision while migrating, add it here.

1. Directory and file structure

The new frontend uses a flat, purpose-named directory layout under app/frontend/. Place every file in the directory that matches its role:

Directory Contents
assets/ Static assets: images and any other files imported into components.
components/ Reusable Vue components used to compose screens. One ComponentName.vue file each.
entrypoints/ Vite entrypoints only. Exactly: application.js, active_admin.js, active_admin.scss.
filters/ Plain filter/formatting functions (see §6). These are functions, not Vue filters.
layouts/ Layout components. Currently only MainLayout.vue.
models/ Spraypaint models and model-like helper classes (e.g. Filters.js).
router/ The vue-router application router (index.js).
stores/ The single Pinia store, AppStore.js.
styles/ Shared, extracted CSS/SCSS. Currently only _variables.scss.
views/ "Page"/"screen" components that routes point to directly.
App.vue The root component (at the root of app/frontend/).

Rules:

  • One component per file. Do not recreate the old ComponentNameComponent/index.vue folder layout. A component named SearchBar lives in components/SearchBar.vue, full stop.
  • The old codebase nested components inside each other's folders (e.g. OrderPageComponent/OrderItemsListComponent/OrderItemComponent/index.vue). Flatten these. Every component becomes a sibling file in components/, regardless of who uses it. Do not recreate the nesting.
  • Co-located assets from the old tree (e.g. CartPreviewComponent/cart-icon.png, TopBarComponent/logo.png) move into assets/.
  • Do not add new top-level directories without a clear reason. If something doesn't fit, prefer an existing directory over inventing a new one.

2. Naming conventions

  • Views (routed screens): drop the old PageComponent/Component suffix and add a View suffix.
    • HomePageComponent → views/HomeView.vue
    • CartPageComponent → views/CartView.vue
    • MyAccountPageComponent → views/MyAccountView.vue
  • Components (everything else): drop the Component suffix entirely.
    • SearchBarComponent → components/SearchBar.vue
    • AppButtonComponent → components/AppButton.vue
    • CartPreviewComponent → components/CartPreview.vue
    • TopBarComponent → components/AppTopBar.vue (renamed for clarity; the shell bar is an "App*" component alongside AppFooter and AppTopBar).
  • Files are PascalCase.vue matching the component name.
  • In templates, reference components with their PascalCase tag name, not the old kebab-case: <SearchBar />, <CartPreview />, <MainMenu />, <RouterLink>, <RouterView />. This matches the reference components and is enabled by explicit local registration (see §3).
  • Deciding view vs component: if a route in router/index.js points at it, it is a view. Otherwise it is a component.

3. Component authoring rules

  • Use the Options API. The new code deliberately keeps the Options API (data, computed, watch, methods, lifecycle hooks, components). Do not convert to <script setup> or the Composition API. One sanctioned exception: a minimal setup() used solely to register cross-component event listeners via mitt-vue's useEventListener (§10). Keep everything else in the Options API — such a setup() should do nothing but register listeners.
  • Register components explicitly and locally. Import each child component and list it in the components: { ... } option of its parent. There is no global component registration anymore.
  • No magic auto-loading. The old application.js used Webpack's require.context to auto-register every App*.vue component globally and every filter as a Vue filter. That entire mechanism is gone. Everything is imported where it is used.
  • Preserve the existing option style. Match the reference files: function-expression options (data: function () { ... }, methods: { foo: function () { ... } }) are used throughout. Keep code style consistent with the surrounding file rather than modernizing syntax gratuitously.
  • Follow Vue's essential (Priority A) style-guide rules. Adhere to the essential rules: use multi-word component names, define detailed prop types/validation (use at least the name: Type form, e.g. props: { listenToChanges: Boolean }, not the terse array form), always key v-for, never use v-if on the same element as v-for, use component-scoped styling (scoped, as the reference components already do), and avoid exposing private state.
  • Order component options per Vue's recommended (Priority C) style guide. Follow the recommended option order. The relevant slice for this Options-API codebase, top to bottom, is: name, components, props, emits, data, computed, watch, lifecycle hooks (in call order: beforeCreate, created, beforeMount, mounted, beforeUpdate, updated, beforeUnmount, unmounted), then methods. Reorder options to match this as you migrate each component.
  • Single-file component top-level element order: <template>, then <script>, then <style>. Apply this consistently, matching the reference components.
  • Lifecycle hook renames: beforeDestroy → beforeUnmount, destroyed → unmounted. (See AppTopBar.vue, which registers/removes listeners in mounted/beforeUnmount.)
  • this.$forceUpdate() still exists and is still used in a couple of places (SearchBar.vue). Don't add new usages, but porting existing ones verbatim is acceptable.

4. Templates and directives

  • Root elements no longer need the old sticky-container attribute; the new App.vue dropped it.

  • The sticky directive package changed from vue-sticky-directive to vue3-sticky-directive (registered as Sticky in application.js). Usage in templates stays the same: v-sticky with an on-stick handler (see AppTopBar.vue).

  • Router components use the PascalCase tags <RouterLink> and <RouterView />.

  • Bind imported image assets rather than referencing static paths. Import the asset and bind it:

    import logoOrigSrc from '../assets/logo-orig.png';
    // ...
    data: function () { return { logoSrc: logoOrigSrc }; }
    <img :src="logoSrc" />

5. Icons: vue-awesome → @fortawesome/vue-fontawesome

vue-awesome does not support Vue 3. It is replaced by Font Awesome's official Vue 3 component. The icon library is registered once in entrypoints/application.js:

import { library } from '@fortawesome/fontawesome-svg-core';
import { fas } from '@fortawesome/free-solid-svg-icons';
import { far } from '@fortawesome/free-regular-svg-icons';
import { fab } from '@fortawesome/free-brands-svg-icons';
library.add(fas, far, fab);

Rules:

  • Import FontAwesomeIcon into each component that needs an icon and register it locally in components: { FontAwesomeIcon }. It is not globally registered.
  • Translate <v-icon name="..." scale="..." /> to <FontAwesomeIcon icon="fa-solid fa-..." size="..." />.
    • The name becomes the second half of the icon string, and you pick the style prefix (fa-solid, fa-regular, fa-brands) explicitly. Old regular-style icons (e.g. name="regular/square") become icon="fa-regular fa-square".
    • Map scale to the nearest size token (e.g. scale="1.5" → size="xl"), matching what the reference components already do.
  • This is a near-mechanical swap; the main judgment call is choosing the correct style prefix.

6. Filters: {{ x | filter }} → function calls

Vue 3 removed template filters (the | syntax). Filters are now ordinary functions.

Rules:

  • Display/formatting filters live in the filters/ directory as plain exported functions: currency, humanDate, orDefault.
  • Call them as regular methods/functions in templates and code. Import the function (or expose it via methods) and invoke it:
    • {{ amount | currency }} → {{ currency(amount) }}
    • {{ order.createdAtDate | humanDate }} → {{ humanDate(order.createdAtDate) }}
    • Chained filters compose as nested calls: {{ item.listPrice | currency | orDefault('-') }} → {{ orDefault(currency(item.listPrice), '-') }}.
  • Do not register anything with Vue.filter(...); that API no longer exists.
  • humanDate in the old code pulled in moment. Prefer not to reintroduce moment; use the platform Intl.DateTimeFormat/Date (or an already-present lightweight helper) when porting it. Do not add new heavy date dependencies without cause.

Naming caution: models/Filters.js is unrelated to the filters/ directory. Filters.js is a route-driven query/URL builder class (shop search filters), and it belongs in models/. The filters/ directory holds view formatting functions. Keep these two concepts separate.


7. State management: Vuex → Pinia

The app uses a single Pinia store, stores/AppStore.js, exported as useAppStore with id 'app'. Pinia supports many stores, but this project intentionally uses only one.

Structural translation from the old Vuex store:

  • Vuex state → Pinia state (a function returning the initial object). Same fields: shopPageLastScrollPosition, basket (a new Cart()), jwt, currentUser.
  • Vuex getters → Pinia getters. Most old getters were trivial passthroughs of state and can be dropped entirely, because components read state directly (see below).
  • Vuex mutations → gone. Pinia has no mutations. Fold each mutation's logic directly into the action(s) that used to commit it. Actions mutate this.<field> directly.
  • Vuex actions → Pinia actions, rewritten to mutate state directly (this.jwt = ...) and to call other actions via this.otherAction() instead of dispatch('otherAction').

Component ↔ store interaction:

  • Read state/getters with Pinia's mapState, imported from 'pinia' (not 'vuex'):

    import { mapState } from 'pinia';
    import { useAppStore } from '../stores/AppStore.js';
    // ...
    computed: {
      ...mapState(useAppStore, ['basket', 'currentUser']),
    },

    mapState in Pinia maps both state fields and getters, so mapGetters is not needed.

  • Replace this.$store.dispatch('foo', payload) with mapActions(useAppStore, ['foo']) + this.foo(payload), or call useAppStore().foo(payload) directly.

  • There is no this.$store. Do not reference it.

Business logic / services: the old codebase kept business logic in services/ classes (CartService, CartApi, UserApi, DomHelper) that were instantiated in application.js and injected into the Vuex store builder. In the new architecture this logic belongs in Pinia actions on AppStore (calling Spraypaint models directly), not in a parallel services layer. Port the behavior of these services into actions as you migrate the features that need them; do not recreate the services/ directory or the store-builder/dependency-injection pattern.

Persistence: the old INIT mutation and SET_JWT/SET_CURRENT_USER mutations read/wrote jwt and currentUser to localStorage. Reproduce this in the store: an init action that hydrates state from localStorage, and actions that keep localStorage in sync when jwt/currentUser change. App.vue already has a beforeCreate hook (currently logging 'startup!') that is the intended place to trigger init.


8. Models (Spraypaint)

Spraypaint works unchanged on Vue 3. Model migration is essentially a copy.

Rules:

  • Keep all models in models/, one class per file, extending ApplicationRecord.
  • ApplicationRecord.js is identical to the old one (same baseUrl, apiNamespace, generateAuthHeader). Do not change it.
  • Port the remaining old models (Product, ProductList, CartItem, Category, InventoryItem, Order, PagePart, PageText) verbatim into models/ as they are needed by the features being migrated. Cart.js and Filters.js are already ported as examples.
  • ApplicationRecord.sync and instance cleanup: see §14. Do not blindly set ApplicationRecord.sync = true without addressing the unlisten() lifecycle, or you will leak listeners.

9. Routing (vue-router)

The router moved to the Vue 3 API (vue-router v4+). See router/index.js.

Rules:

  • Create the router with createRouter({ history: createWebHistory(), routes: [...] }). There is no new Router({ mode: 'history' }) and no Vue.use(VueRouter); the router is installed with app.use(router) in application.js.
  • Route components are imported explicitly (views from views/, e.g. import HomeView from '../views/HomeView.vue').
  • Port the old routes into the new routes array. Preserve each route's path, and translate the name to the new view name (e.g. HomePageComponent → home).
  • Route params / path matching: the old routes used long inline path-regex strings (e.g. the /shop(/l/)?:productListSlug(...)... pattern) to encode the shop/reorder filter URLs. vue-router v4 changed the path-ranking/regex syntax. Re-express these using the v4 param syntax (custom regex in the :param(regex) form, repeatable/optional segments) so the same URLs still resolve. The Filters model (models/Filters.js) is the source of truth for how these URL segments map to filter state — keep Filters#toPath and Filters#clear(route) in sync with the route definitions.
  • Port scrollBehavior as-is (including the special-case that avoids scrolling to top during shop "load more" pagination).
  • Old routes passed data via props: { ... } and instantiated services there (e.g. props: { userApi: new UserApi() }). Since services are being folded into the store (§7), drop those service props; views should reach the store/models directly instead.
  • meta: { breadcrumb: '...' } entries are retained on routes but the breadcrumb rendering is deferred (see §14).

10. Event bus: Vue-instance bus → mitt-vue

The old codebase implemented a cross-component event bus with EventBus.js (export const EventBus = new Vue()) and used EventBus.$emit(...) / EventBus.$on(...). Vue 3 instances are not event emitters, so this pattern is gone. It is replaced by mitt-vue (built on mitt), which exposes a single shared emitter at module scope.

Rules:

  • No install / no application.js wiring. The shared emitter is created when mitt-vue is imported; there is nothing to register with app.use(...). Just import its helpers where needed.
  • Emit with eventEmit(name, payload) (imported from mitt-vue, alias as you like, e.g. import { useEventEmit as eventEmit } from 'mitt-vue'). It is a plain function, callable from anywhere — Options-API methods, lifecycle hooks, etc.
    • EventBus.$emit('refreshed', data) → eventEmit('refreshed', data).
  • Listen with useEventListener(name, handler) from mitt-vue, called inside a component setup() hook. It registers the handler on mount and removes it on unmount automatically — so there is no manual off() / beforeUnmount teardown and no leaks (the old Vue-instance bus never cleaned up).
    • EventBus.$on('refreshed', handler) → useEventListener('refreshed', handler) in setup().
    • Because useEventListener must run in setup(), this is the single sanctioned Composition-API touchpoint in an otherwise Options-API codebase (see §3): add a minimal setup() that only registers listeners; keep everything else in the Options API.
    • Do not try to on()/off() the shared emitter imperatively from Options-API hooks — mitt-vue does not export the raw emitter, so useEventListener is the only way to subscribe to the shared bus.
  • Keep event names identical to the old ones where the counterpart component hasn't been migrated yet, so partially-migrated features keep working (e.g. 'refreshed', 'inventory-item-refreshed-<id>').
  • Do not recreate EventBus.js.

11. Real-time: actioncable-vue

actioncable-vue supports Vue 3, so this is mostly a configuration/adaptation change rather than a replacement.

Rules:

  • Install and configure ActionCableVue in entrypoints/application.js via app.use(...), porting the old options (debug settings and the connectionUrl derived from window.socketConnectionUrl / window.location).
  • The channels: { ... } component option and this.$cable.subscribe({ channel, room }, 'handler') usage carry over (see the ported-but-commented CartPreview.vue for the intended shape). Re-enable these as the corresponding store actions/models are migrated.
  • Replace old this.$console.log(...) calls inside channel handlers with plain console.log(...) (see §12).

12. Logger removal

The old app had a Logger service and a LoggerComponent, installed as a Vue plugin exposing this.$console and an on-screen log sink.

Rules:

  • Do not migrate the logger. There is no LoggerComponent, no Logger service, and no this.$console.
  • Replace every this.$console.log/warn/error(...) with the standard console.log/warn/error(...).
  • The commented-out <logger /> / LoggerComponent references in App.vue are leftovers slated for deletion, not TODOs to wire up.

13. Bootstrapping (entrypoints/application.js) and polyfills

The old packs/application.js did a lot of imperative bootstrapping: polyfills, require.context auto-registration, manual Vue.use(...) for every plugin, DOM node creation on DOMContentLoaded, and new Vue({ el, router, store, ... }). The new entrypoint is deliberately small and declarative.

Rules:

  • App creation follows the Vue 3 pattern already in place:

    const app = createApp(App);
    app.use(createPinia());
    app.use(router);
    app.use(AsyncComputed);
    app.use(Sticky);
    app.mount('#app');

    Register additional plugins (Font Awesome library setup, ActionCable, mitt) here as features need them, following the same style.

  • Remove all polyfills. Do not port babel-polyfill, core-js/fn/promise/finally, or whatwg-fetch. Modern browsers and the Vite toolchain cover these.

  • Do not port the require.context auto-registration of components or filters, the document.addEventListener('DOMContentLoaded', ...) bootstrapping, or the manual app DOM-node creation. Components mount into the existing #app element.

  • vue-async-computed (the asyncComputed component option) is still used; it is installed as AsyncComputed. Port asyncComputed options as-is where old components used them.


14. Deferred work (tackle these last)

These items don't have a clean Vue 3 drop-in replacement and are intentionally postponed until the bulk of the straightforward migration is done. Leave them stubbed/commented in the meantime rather than blocking on them.

  • Breadcrumbs (vue-breadcrumbs). No Vue 3 equivalent. The old AppBreadcrumbsComponent and the library integrated with the router via meta.breadcrumb and this.$breadcrumbs. Keep the meta: { breadcrumb: '...' } entries on routes (§9) and, at the end, implement a small breadcrumbs component that reads to.matched/meta.breadcrumb from the current route instead of relying on the removed $breadcrumbs global.
  • Carousel (vue-carousel). No clean Vue 3 replacement. Used by ItemCarouselComponent and HeroImageComponent (the <carousel :perPage="..."> element). Defer; later either adopt a Vue-3-compatible carousel or implement a minimal one. Preserve the responsive perPage behavior.
  • Notifications (vue-notification). No clean Vue 3 replacement. Old code used <notifications ... /> plus this.$notify({ ... }) (see the commented blocks in CartPreview.vue and App.vue). Defer; later replace with a Vue-3-compatible toast or a small custom implementation, preserving the warn/error/success styles already present in App.vue's stylesheet.
  • Spraypaint listener cleanup (spraypaint-vue). No Vue 3 support. Its only job was to enhance Spraypaint's sync feature so model instances call #unlisten() when the owning component is destroyed, preventing memory leaks when ApplicationRecord.sync = true. Decide late whether sync is actually needed; if it is, reimplement this small behavior for Vue 3 (call unlisten() in beforeUnmount, e.g. via a mixin or a tiny plugin/directive) rather than pulling in the old package. Until then, be cautious about enabling ApplicationRecord.sync = true.

15. Styles / SCSS

  • Shared SCSS variables live in styles/_variables.scss (replacing the old components/shared/_variables.scss). Consume them with the module system:

    @use '../styles/variables' as *;

    Do not use the deprecated @import for these.

  • Keep component styles in the component's <style scoped lang="scss"> block. Port old component CSS as-is; scope it (scoped) unless it was intentionally global.

  • foundation-sites CSS is imported once in application.js (import 'foundation-sites/dist/css/foundation.css'). Don't re-import it per component.


16. Code style

  • Prettier governs formatting: single quotes, semicolons, printWidth: 120 (see .prettierrc.json). ESLint uses the flat config with eslint-plugin-vue essentials.
  • Run the frontend through the existing tooling (npm/Vite) after migrating a file; keep it lint- and format-clean.

17. Testing

The old codebase carried a tests/ suite (Jest-style specs for components, filters, services, models, and the Vuex store). There is no frontend automated test coverage in the new app yet, and the AGENTS guidance notes frontend changes are validated manually for now. Do not port the old specs wholesale. Migrate frontend features first and validate them manually; introduce a test setup deliberately as a separate decision rather than as a side effect of migrating a component.


18. Per-component migration checklist

When migrating a single old component, work through this list:

  1. Locate & rename — find it under old_codebase/.../SomethingComponent/index.vue. Decide view vs component (§2), pick the new name, and create views/SomethingView.vue or components/Something.vue.
  2. Template — update component tags to PascalCase, convert filter pipes to function calls (§6), swap <v-icon> for <FontAwesomeIcon> (§5), and adjust directives (§4).
  3. Script — keep the Options API; import and locally register child components, FontAwesomeIcon, and filter functions; rename lifecycle hooks (§3); replace $console with console (§12).
  4. Store — replace mapGetters/$store.dispatch/mapState from Vuex with Pinia equivalents (§7).
  5. Models/services — import Spraypaint models directly; fold any needed service logic into store actions (§7, §8).
  6. Events/realtime — migrate EventBus usage to the mitt emitter (§10) and re-enable $cable channels where their dependencies exist (§11).
  7. Assets & styles — move co-located images into assets/ and import them; port styles with @use for variables (§4, §15).
  8. Deferred deps — if it depends on breadcrumbs, carousel, or notifications, stub/comment that part and leave a note (§14).
  9. Router — if it's a view, add/adjust its route in router/index.js (§9).
  10. Validate — lint/format, then manually verify in the running app (§16, §17).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment