
Vue Router V3
- 25 installs
- 2 repo stars
- Updated July 29, 2026
- full-statck-skills/vue-skills
Guidance for Vue Router v3 routing setup, navigation patterns and API for Vue 2 applications.
About
Provides Vue Router v3 guidance for installation, routing patterns, navigation guards, history mode and lazy loading in Vue 2 apps. A developer uses it when routing a Vue 2 application.
- Covers install and config of Vue Router v3
- Includes navigation guards, history mode and lazy-loading routes
Vue Router V3 by the numbers
- 25 all-time installs (skills.sh)
- Ranked #1,501 of 2,245 Frontend Development skills by installs in the Skillselion catalog
- Data as of Jul 30, 2026 (Skillselion catalog sync)
npx skills add https://github.com/full-statck-skills/vue-skills --skill vue-router-v3Add your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 25 |
|---|---|
| repo stars | ★ 2 |
| Last updated | July 29, 2026 |
| Repository | full-statck-skills/vue-skills ↗ |
What it does
Guidance for Vue Router v3 routing setup, navigation patterns and API for Vue 2 applications.
Files
When to use this skill
Use this skill whenever the user wants to:
- Install and configure Vue Router v3
- Implement routing patterns for Vue 2 applications
- Use navigation guards, history mode, or lazy-loading routes
- Reference Vue Router v3 API details
How to use this skill
1. Identify the topic from the user request. 2. Open the matching guide example file in examples/. 3. For API details, open the matching file in api/. 4. Follow official guidance and keep outputs consistent with v3 docs.
Installation mapping
examples/installation.md→ https://v3.router.vuejs.org/installation.html
Guide mapping (one-to-one with https://v3.router.vuejs.org/guide/)
Essentials
examples/guide/index.md→ https://v3.router.vuejs.org/guide/examples/guide/essentials/dynamic-matching.md→ https://v3.router.vuejs.org/guide/essentials/dynamic-matching.htmlexamples/guide/essentials/nested-routes.md→ https://v3.router.vuejs.org/guide/essentials/nested-routes.htmlexamples/guide/essentials/navigation.md→ https://v3.router.vuejs.org/guide/essentials/navigation.htmlexamples/guide/essentials/named-routes.md→ https://v3.router.vuejs.org/guide/essentials/named-routes.htmlexamples/guide/essentials/named-views.md→ https://v3.router.vuejs.org/guide/essentials/named-views.htmlexamples/guide/essentials/redirect-and-alias.md→ https://v3.router.vuejs.org/guide/essentials/redirect-and-alias.htmlexamples/guide/essentials/passing-props.md→ https://v3.router.vuejs.org/guide/essentials/passing-props.htmlexamples/guide/essentials/history-mode.md→ https://v3.router.vuejs.org/guide/essentials/history-mode.html
Advanced
examples/guide/advanced/navigation-guards.md→ https://v3.router.vuejs.org/guide/advanced/navigation-guards.htmlexamples/guide/advanced/meta.md→ https://v3.router.vuejs.org/guide/advanced/meta.htmlexamples/guide/advanced/transitions.md→ https://v3.router.vuejs.org/guide/advanced/transitions.htmlexamples/guide/advanced/data-fetching.md→ https://v3.router.vuejs.org/guide/advanced/data-fetching.htmlexamples/guide/advanced/scroll-behavior.md→ https://v3.router.vuejs.org/guide/advanced/scroll-behavior.htmlexamples/guide/advanced/lazy-loading.md→ https://v3.router.vuejs.org/guide/advanced/lazy-loading.htmlexamples/guide/advanced/navigation-failures.md→ https://v3.router.vuejs.org/guide/advanced/navigation-failures.html
API mapping (one-to-one with https://v3.router.vuejs.org/api/)
api/router-link.md→ https://v3.router.vuejs.org/api/#router-linkapi/router-view.md→ https://v3.router.vuejs.org/api/#router-viewapi/router-instance.md→ https://v3.router.vuejs.org/api/#router-instanceapi/router-options.md→ https://v3.router.vuejs.org/api/#router-optionsapi/route-object.md→ https://v3.router.vuejs.org/api/#the-route-objectapi/route-config.md→ https://v3.router.vuejs.org/api/#routesapi/navigation-guards.md→ https://v3.router.vuejs.org/api/#navigation-guards
Resources
- Installation: https://v3.router.vuejs.org/installation.html
- Guide: https://v3.router.vuejs.org/guide/
- API: https://v3.router.vuejs.org/api/
Keywords
vue-router v3, vue 2 router, routing, navigation guards, history mode, router-link, router-view, route config, route object
国内适配
- 支持中文文档和中文注释
- 示例代码兼容国内开发环境
- 提供中文 FAQ 和常见问题解答
能力边界
✅ 适用场景
- 当你需要使用此技能对应的技术栈时
- 当项目需要遵循最佳实践时
- 当需要快速上手或深入理解核心概念时
⚠️ 需要注意
- 复杂业务逻辑需要结合具体场景调整
- 性能优化需要根据实际数据量评估
❌ 不适用场景
- 不相关的技术栈或框架
- 需要完全自定义的特殊场景
使用流程
Step 1: 环境准备
确保开发环境已安装必要的依赖和工具。
Step 2: 配置初始化
根据项目需求进行基础配置。
Step 3: 核心功能使用
按照示例代码实现核心功能。
Step 4: 测试验证
运行测试确保功能正常。
Step 5: 部署上线
完成开发后进行部署和监控。
Instructions
Use this API section to confirm options for navigation guards.
Examples
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isLoggedIn()) {
next('/login')
} else {
next()
}
})export default {
beforeRouteLeave(to, from, next) {
// confirm leave
next()
}
}Scenarios
Auth and role checks
- Use global guards with meta roles.
- Redirect or block appropriately.
router.beforeEach((to, from, next) => {
const role = getUserRole()
if (to.meta.role && to.meta.role !== role) {
next('/403')
} else {
next()
}
})Unsaved changes
- Use beforeRouteLeave for confirmation.
- Prevent accidental navigation loss.
export default {
beforeRouteLeave(to, from, next) {
const ok = window.confirm('Discard changes?')
next(ok)
}
}Reference: https://v3.router.vuejs.org/api/#navigation-guards
Parameters
beforeEach/beforeResolve/afterEach- Global hooks.beforeEnter- Per-route guard.beforeRouteEnter/beforeRouteUpdate/beforeRouteLeave- In-component.
Returns
- Guards control navigation flow via
next(). - After hooks run after navigation completes.
Common Errors
- Not calling next() blocks navigation.
- Calling next() multiple times causes errors.
Best Practices
- Use meta fields to centralize access control.
- Prefer async/await with try/catch in guards.
Instructions
Use this API section to confirm options for route config.
Examples
const routes = [
{ path: '/', component: Home },
{ path: '/user/:id', name: 'user', component: User, props: true }
]const routes = [
{
path: '/user/:id',
component: User,
children: [
{ path: 'profile', component: UserProfile }
]
}
]Scenarios
Nested user routes
- Use children for nested UI.
- Keep child paths relative.
const routes = [
{
path: '/user/:id',
component: User,
children: [
{ path: 'profile', component: UserProfile },
{ path: 'posts', component: UserPosts }
]
}
]Passing props
- Use props: true to simplify components.
- Avoid direct $route usage in components.
{ path: '/user/:id', component: User, props: true }Reference: https://v3.router.vuejs.org/api/#routes
Parameters
path(string) - URL path pattern.component/components- Component(s) to render.name(string) - Named route.children(Array<RouteConfig>) - Nested routes.redirect/alias- Routing aliases.props(boolean | object | function) - Pass props.
Returns
- Defines how URLs map to components.
- Nested routes create nested UI via router-view.
Common Errors
- Missing leading slash in path for top-level routes.
- Conflicting paths lead to unexpected matches.
Best Practices
- Use names for stable navigation.
- Prefer lazy loading for large route components.
Instructions
Use this API section to confirm options for route object.
Examples
export default {
computed: {
userId() {
return this.$route.params.id
}
}
}router.beforeEach((to, from, next) => {
const requiresAuth = to.matched.some(r => r.meta.requiresAuth)
next(requiresAuth ? '/login' : true)
})Scenarios
Reading params and query
- Prefer props for params when possible.
- Use $route.query for filters.
export default {
computed: {
userId() { return this.$route.params.id },
q() { return this.$route.query.q }
}
}Meta-based access
- Use matched records to read meta.
- Centralize access checks in guards.
const requiresAuth = this.$route.matched.some(r => r.meta.requiresAuth)Reference: https://v3.router.vuejs.org/api/#the-route-object
Parameters
$route.path- Current path.$route.params- Dynamic params.$route.query- Query parameters.$route.hash- Hash fragment.$route.matched- Matched route records.
Returns
- Route object describes the current location.
- Reactive and updates on navigation.
Common Errors
- Directly mutating $route is unsupported.
- Reading params not defined on route yields undefined.
Best Practices
- Prefer props over $route where possible.
- Use matched records for meta checks.
Instructions
Use this API section to confirm options for router instance.
Examples
// programmatic navigation
this.$router.push({ name: 'user', params: { id: 1 } })
this.$router.replace('/login')// global guard
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isLoggedIn()) {
next('/login')
} else {
next()
}
})Scenarios
Guarded routes
- Check meta flags before navigation.
- Redirect to login when unauthenticated.
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isLoggedIn()) {
next('/login')
} else {
next()
}
})Error handling
- Handle NavigationDuplicated errors gracefully.
- Avoid unhandled promise rejections.
this.$router.push('/same').catch(() => {})Reference: https://v3.router.vuejs.org/api/#router-instance
Parameters
router.push(location)- Navigate to a new route.router.replace(location)- Replace current history entry.router.go(n)- Move forward/back in history.router.back()/router.forward()- History helpers.router.beforeEach(fn)- Global guard.router.afterEach(fn)- Global after hook.
Returns
- Most navigation methods return a Promise.
- Guards return control via
next()callbacks.
Common Errors
- Unhandled NavigationDuplicated errors on same route.
- Missing
next()in guards causes navigation to hang.
Best Practices
- Use named routes for push/replace.
- Handle promise rejections from push/replace.
- Keep guards minimal and async-safe.
Instructions
Use this API section to confirm options for router link.
Examples
<router-link :to="{ name: 'user', params: { id: 42 } }">
User 42
</router-link><router-link to="/about" exact>About</router-link>Scenarios
Authentication-aware navigation
- Use named routes to avoid brittle paths.
- Use exact-active-class for precise styling.
<router-link
:to="{ name: 'dashboard' }"
exact-active-class="is-active"
>
Dashboard
</router-link>External links vs router-link
- Use <a> for external URLs.
- Keep router-link for internal navigation only.
<a href="https://example.com" target="_blank" rel="noopener">Docs</a>Reference: https://v3.router.vuejs.org/api/#router-link
Parameters
to(string | Location Object) - Target location.tag(string) - Rendered tag (default:a).replace(boolean) - Usereplaceinstead ofpush.append(boolean) - Append to current path.exact(boolean) - Apply active class only on exact match.active-class/exact-active-class- Custom active classes.event(string | array) - Trigger events (default:click).
Returns
- Renders a link component that updates route when activated.
- Applies active classes based on current route.
Common Errors
- Using invalid
toformat leads to navigation errors. - Forgetting
exactcauses active class to match child routes.
Best Practices
- Prefer named routes in
tofor stability. - Use
exact-active-classfor precise styling. - Avoid nesting router-links inside anchors.
Instructions
Use this API section to confirm options for router options.
Examples
const router = new VueRouter({
mode: 'history',
base: '/app/',
routes
})const router = new VueRouter({
routes,
scrollBehavior(to, from, savedPosition) {
return savedPosition || { x: 0, y: 0 }
}
})Scenarios
History mode on production
- Enable history mode for clean URLs.
- Ensure server rewrite to index.html.
const router = new VueRouter({
mode: 'history',
routes
})Scroll restoration
- Restore saved position on back/forward.
- Reset to top on new navigation.
const router = new VueRouter({
routes,
scrollBehavior(to, from, savedPosition) {
return savedPosition || { x: 0, y: 0 }
}
})Reference: https://v3.router.vuejs.org/api/#router-options
Parameters
routes(Array<RouteConfig>) - Route definitions.mode(string) -hashorhistory.base(string) - Base URL for the app.scrollBehavior(function) - Scroll restoration.linkActiveClass/linkExactActiveClass- Global classes.
Returns
- Creates a router instance with the provided configuration.
Common Errors
- History mode without server fallback causes 404 on refresh.
- Incorrect base leads to broken links.
Best Practices
- Use history mode with proper server rewrite.
- Centralize scrollBehavior for SPA UX.
Instructions
Use this API section to confirm options for router view.
Examples
<router-view />
<router-view name="sidebar" />const routes = [
{
path: '/dashboard',
components: {
default: Dashboard,
sidebar: Sidebar
}
}
]Scenarios
Layout with sidebar
- Render default and named views for layout regions.
- Keep layout components thin.
<router-view />
<router-view name="sidebar" />Nested routes outlet
- Place router-view inside parent to render children.
- Use nested routes for sub-sections.
<!-- Parent.vue -->
<router-view />Reference: https://v3.router.vuejs.org/api/#router-view
Parameters
name(string) - Named view to render (default:default).
Returns
- Renders the matched component for the current route.
- Supports named views for multiple outlets.
Common Errors
- Missing
<router-view>yields no route component output. - Name mismatch prevents named view from rendering.
Best Practices
- Keep a single router-view per layout region.
- Use named views only when needed.
Instructions
- Fetch data before navigation or in component.
- Handle loading states.
- Cancel stale requests on route change.
Example
export default {
data() { return { loading: false, post: null } },
watch: {
'$route.params.id': {
immediate: true,
handler(id) {
// fetch post by id
}
}
}
}Reference: https://v3.router.vuejs.org/guide/advanced/data-fetching.html
Instructions
- Use dynamic imports for route components.
- Split bundles by route.
- Use webpackChunkName for naming chunks.
Example
const User = () => import(/* webpackChunkName: "user" */ './User.vue')
const routes = [
{ path: '/user/:id', component: User }
]Reference: https://v3.router.vuejs.org/guide/advanced/lazy-loading.html
Instructions
- Attach meta fields to routes.
- Read meta in guards for access control.
- Use meta for titles or permissions.
Example
const routes = [
{ path: '/admin', component: Admin, meta: { requiresAuth: true } }
]Example
router.beforeEach((to, from, next) => {
const requiresAuth = to.matched.some(r => r.meta.requiresAuth)
next(requiresAuth ? '/login' : true)
})Reference: https://v3.router.vuejs.org/guide/advanced/meta.html
Instructions
- Handle navigation failures from redundant navigation.
- Use router.onError or router.push().catch.
- Use isNavigationFailure when needed.
Example
this.$router.push('/same').catch(err => {
// ignore NavigationDuplicated
})Reference: https://v3.router.vuejs.org/guide/advanced/navigation-failures.html
Instructions
- Use global guards for auth checks.
- Use per-route and in-component guards.
- Always call next() to resolve navigation.
Example
router.beforeEach((to, from, next) => {
// Check auth
if (to.meta.requiresAuth && !isLoggedIn()) {
next('/login')
} else {
next()
}
})Example
export default {
beforeRouteLeave(to, from, next) {
// confirm leave
next()
}
}Reference: https://v3.router.vuejs.org/guide/advanced/navigation-guards.html
Instructions
- Implement scrollBehavior for saved position.
- Return coordinates or selector.
- Use for SPA scroll restoration.
Example
const router = new VueRouter({
routes,
scrollBehavior(to, from, savedPosition) {
if (savedPosition) return savedPosition
return { x: 0, y: 0 }
}
})Reference: https://v3.router.vuejs.org/guide/advanced/scroll-behavior.html
Instructions
- Wrap router-view with <transition>.
- Use transition mode for proper sequencing.
- Use dynamic transitions if needed.
Example
<transition name="fade" mode="out-in">
<router-view />
</transition>Reference: https://v3.router.vuejs.org/guide/advanced/transitions.html
Instructions
- Use dynamic segments with params.
- Access params via $route.params.
- Update components when params change.
Example
const routes = [
{ path: '/user/:id', component: User }
]Example
export default {
// Handle param changes
watch: {
'$route.params.id'(id) {
// fetch user with id
}
}
}Reference: https://v3.router.vuejs.org/guide/essentials/dynamic-matching.html
Instructions
- Enable history mode for clean URLs.
- Ensure server fallback to index.html.
- Use hash mode when server config is not possible.
Example
const router = new VueRouter({
mode: 'history',
routes
})Example
Server must redirect all routes to index.htmlReference: https://v3.router.vuejs.org/guide/essentials/history-mode.html
Instructions
- Give routes a name for stable navigation.
- Use name in router-link and router.push.
- Prefer names over hard-coded paths.
Example
const routes = [
{ path: '/user/:id', name: 'user', component: User }
]Example
this.$router.push({ name: 'user', params: { id: 123 } })Reference: https://v3.router.vuejs.org/guide/essentials/named-routes.html
Instructions
- Use named views to render multiple views.
- Define components object per route.
- Use named <router-view> outlets.
Example
const routes = [
{
path: '/dashboard',
components: {
default: Dashboard,
sidebar: Sidebar
}
}
]Example
<router-view />
<router-view name="sidebar" />Reference: https://v3.router.vuejs.org/guide/essentials/named-views.html
Instructions
- Use <router-link> for declarative navigation.
- Use this.$router.push for programmatic navigation.
- Prefer named routes for maintainability.
Example
<router-link :to="{ name: 'profile', params: { id: 1 } }">Profile</router-link>Example
export default {
methods: {
// Navigate to profile
goProfile() {
this.$router.push({ name: 'profile', params: { id: 1 } })
}
}
}Reference: https://v3.router.vuejs.org/guide/essentials/navigation.html
Instructions
- Define children routes for nested UI.
- Use <router-view> in parent components.
- Keep nested paths relative.
Example
const routes = [
{
path: '/user/:id',
component: User,
children: [
{ path: 'profile', component: UserProfile },
{ path: 'posts', component: UserPosts }
]
}
]Example
<!-- User.vue -->
<router-view />Reference: https://v3.router.vuejs.org/guide/essentials/nested-routes.html
Instructions
- Use props: true to pass params as props.
- Use function mode for custom mapping.
- Prefer props over $route in components.
Example
const routes = [
{ path: '/user/:id', component: User, props: true }
]Example
{ path: '/search', component: Search, props: route => ({ q: route.query.q }) }Reference: https://v3.router.vuejs.org/guide/essentials/passing-props.html
Instructions
- Use redirect to forward routes.
- Use alias to map multiple paths to same route.
- Keep redirects explicit.
Example
const routes = [
{ path: '/home', redirect: '/' },
{ path: '/user/:id', component: User, alias: '/u/:id' }
]Reference: https://v3.router.vuejs.org/guide/essentials/redirect-and-alias.html
Instructions
- Introduce core routing concepts.
- Explain route mapping and router-view.
- Use as the entry point for all guide topics.
Example
// routes.js
export const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]Example
<router-view />Notes
- Use <router-link> for navigation.
Reference: https://v3.router.vuejs.org/guide/
Instructions
- Install Vue Router v3 via npm or yarn.
- Register the router with Vue.
- Create a router instance and mount the app.
Example
npm install vue-router@3Example
import Vue from 'vue'
import VueRouter from 'vue-router'
// Register router plugin
Vue.use(VueRouter)Notes
- Use Vue 2 with vue-router@3.
Reference: https://v3.router.vuejs.org/installation.html
Route Configuration Templates
Basic Route
{
path: '/home',
component: Home
}Named Route
{
path: '/user/:id',
name: 'user',
component: User
}Route with Children
{
path: '/user/:id',
component: User,
children: [
{
path: 'profile',
component: Profile
},
{
path: 'posts',
component: Posts
}
]
}Route with Redirect
{
path: '/home',
redirect: '/'
}Route with Alias
{
path: '/home',
component: Home,
alias: '/'
}Route with Props
{
path: '/user/:id',
component: User,
props: true
}Route with Meta
{
path: '/admin',
component: Admin,
meta: {
requiresAuth: true,
requiresAdmin: true
}
}Route with BeforeEnter Guard
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => {
if (isAdmin()) {
next()
} else {
next('/')
}
}
}Lazy Loaded Route
{
path: '/about',
component: () => import('@/views/About.vue')
}Route with Named Views
{
path: '/',
components: {
default: Home,
header: Header,
footer: Footer
}
}Router Configuration Templates
Basic Router Configuration
// router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/Home.vue'
Vue.use(VueRouter)
const routes = [
{ path: '/', component: Home }
]
const router = new VueRouter({
routes
})
export default routerRouter with History Mode
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{ path: '/', component: Home }
]
})
export default routerRouter with Custom Active Classes
const router = new VueRouter({
routes: [...],
linkActiveClass: 'active',
linkExactActiveClass: 'exact-active'
})Router with Scroll Behavior
const router = new VueRouter({
routes: [...],
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
return { x: 0, y: 0 }
}
}
})Router with Navigation Guards
const router = new VueRouter({
routes: [...]
})
router.beforeEach((to, from, next) => {
// Authentication check
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!isAuthenticated()) {
next('/login')
} else {
next()
}
} else {
next()
}
})
export default router