Introduction to Vue Router
Vue Router serves as the official routing library for Vue.js applications, providing seamless integration with Vue's core functionality. It enables developers to build sophisticated single-page aplications (SPAs) by managing navigation between views without full page reloads.
Routing Instance Configuration
import { createRouter, createWebHistory } from 'vue-router'
import Dashboard from '../components/Dashboard.vue'
import Profile from '../components/Profile.vue'
const routeDefinitions = [
{ path: '/dashboard', component: Dashboard },
{ path: '/profile', component: Profile }
]
const routingInstance = createRouter({
history: createWebHistory(),
routes: routeDefinitions
})
export default routingInstance
<template>
<router-link to="/dashboard">Dashboard</router-link>
<router-link to="/profile">Profile</router-link>
<router-view></router-view>
</template>
Routing Modes
Vue Router supports two primary routing modes: history mode (using createWebHistory) which produces clean URLs like http://localhost:8080/dashboard, and hash mode (using createWebHashHistory) wich includes hash symbols like http://localhost:8080/#/dashboard.
Named Routes and Dynamic Parameters
const routeDefinitions = [
{ path: '/user/:userId', name: 'userProfile', component: UserProfile }
]
<router-link :to="{ name: 'userProfile', params: { userId: 456 } }">
User Profile
</router-link>
Programmatic Navigation
import { useRouter } from 'vue-router'
const router = useRouter()
function navigateToProfile() {
router.push({ name: 'userProfile', params: { userId: 789 } })
}
Route Parameters and Query Strings
import { useRoute } from 'vue-router'
const currentRoute = useRoute()
const userId = currentRoute.params.userId
const searchQuery = currentRoute.query.search
Nested Routes and Named Views
const routeDefinitions = [{
path: '/settings',
component: SettingsLayout,
children: [
{ path: 'account', component: AccountSettings },
{ path: 'privacy', component: PrivacySettings }
]
}]
Route Redirection and Aliases
const routeDefinitions = [
{ path: '/admin', redirect: '/dashboard' },
{ path: '/home', component: HomePage, alias: '/welcome' }
]
Route Props Configuration
const routeDefinitions = [
{
path: '/product/:productId',
component: ProductDetail,
props: route => ({ productId: parseInt(route.params.productId) })
}
]