Vue Router v5 Best Practices
Overview
Treat Vue Router v5 as the default routing stack for new work. Use classic route records when the app already depends on them, and use the new core file-based routing and data loader APIs when the codebase needs typed routes, route-scoped data, or migration from unplugin-vue-router.
Workflow
Identify the routing style first.
- Use
createRouterwith classic route records when the app already defines routes manually. - Use
vue-router/vitewhen the app uses file-based routing in Vite. - Use
vue-router/unpluginfor Webpack, Rollup, or esbuild integration. - Use
vue-router/experimentalfor data loaders. - Use
vue-router/volar/*plugins when you need typed SFC route blocks and typed routes in Volar.
- Use
Apply file-based routing conventions deliberately.
- Treat
src/pagesas the default route root. - Use
index.vuefor index routes,[id].vuefor params,[[id]].vuefor optional params,[slugs]+.vuefor repeatable params, and[...path].vuefor catch-all routes. - Use
(group)folders to organize routes without changing URLs. - Use
@namesuffixes for named views. - Use
definePage({ name: ... })when a route needs an explicit name.
- Treat
Handle navigation with return-based guards.
- Use
router.beforeEach,router.beforeResolve,beforeEnter,beforeRouteUpdate, andbeforeRouteLeaveas needed. - Return
falseto cancel a navigation and return a route location to redirect. - Use
next()only when working with legacy guard code that already depends on it. - Use
beforeRouteUpdateoronBeforeRouteUpdatewhen the same component stays mounted and only params, query, or hash change.
- Use
Use data loaders for route-scoped async state.
- Install
DataLoaderPluginbefore the router when using data loaders. - Define loaders with
defineBasicLoader,defineLoader, ordefineColadaLoaderas the use case requires. - Treat the
toargument as the source of truth for fetch inputs. - Avoid side effects in loader bodies.
- Use
reroute()to redirect or cancel from a loader. - Use
lazywhen data should load after navigation instead of blocking it.
- Install
Migrate safely from older setups.
- If the app is on Vue Router 4 without
unplugin-vue-router, upgrading to v5 should not require code changes. - If the app uses
unplugin-vue-router, update the plugin and utility imports to the newvue-router/*entry points. - Move generated route types to
typed-router.d.tsor another file that is included by TypeScript.
- If the app is on Vue Router 4 without
Watch lifecycle and UX edges.
- Clean up listeners in component teardown when route components are reused.
- Refetch or reset local state when route params change but the component instance is reused.
- Define
scrollBehaviorwhen navigation should restore or override scroll position.
References
Source: wicii2120/skills — distributed by TomeVault.