Vue Router
Basic Routing with Vue Router
Vue Router is a powerful and flexible routing library that integrates with Vue.js to manage navigation in your application. It allows you to map URLs (or paths) to specific Vue components, creating a smooth and interactive user experience within a single-page application. Instead of navigating to entirely new HTML pages for different sections of your application, Vue Router dynamically renders components within the same page based on the URL.
const routes = [
{
path: "/",
name: "Home",
component: Home
},
{
path: "/about",
name: "About",
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () =>
import(/* webpackChunkName: "about" */ "../views/About.vue")
}
];
<router-view>
Component: A special component provided by Vue Router. You place <router-view>
in your template where you want the matched component for the current route to be rendered. It acts as a placeholder that gets dynamically filled with the component associated with the current URL.
<router-link>
Component: The primary way to navigate between routes in your templates. It's similar to an <a>
tag but prevents full page reloads and triggers Vue Router's internal navigation.
<template>
<div id="app">
<nav>
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</nav>
<router-view></router-view> <!-- Component for current route renders here -->
</div>
</template>
History Mode
Vue Router offers two modes for managing the URL:
Hash Mode (default): Uses the hash portion of the URL (#). URLs look like http://example.com/#/path. Simpler to configure, works without server-side configuration.
History Mode: Uses the HTML5 History API for cleaner URLs without the hash (e.g., http://example.com/path). Requires server-side configuration to correctly handle direct access to routes and page reloads. Often preferred for user experience and SEO.
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '/user/:id', component: User }, //route parameters
{ path: '*', component: NotFoundComponent } //Catch all route
]
})
There is a caveat to using "History mode": Your server will no longer report 404 errors as all not-found paths now serve up your index.html
file. To get around the issue, you should implement a catch-all route within your Vue app to show a 404 page.
Nested Routes
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User,
children: [
{
// UserProfile will be rendered inside User's <router-view>
// when /user/:id/profile is matched
path: 'profile',
component: UserProfile
},
{
// UserPosts will be rendered inside User's <router-view>
// when /user/:id/posts is matched
path: 'posts',
component: UserPosts
}
]
}
]
})
Route Guards
As the name suggests, the navigation guards provided by vue-router
are primarily used to guard navigations either by redirecting it or canceling it. There are a number of ways to hook into the route navigation process: globally, per-route, or in-component.
// Global navigation guard example
router.beforeEach((to, from, next) => {
if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
else next()
})
Programmatic Navigation with Route Helpers
You can navigate programmatically from within your JavaScript code using the router instance injected into your components.
this.$router.push('/path')
: Navigate to a new path (adds to history).this.$router.replace('/path')
: Navigate to a new path (replaces current history entry).this.$router.go(n)
: Navigate forward or backward in history (like browser history buttons).this.$router.back()
: Go back one step in history.this.$router.forward()
: Go forward one step in history.
// Home.vue
export default {
computed: {
id() {
return this.$route.params.id //using route params in methods or CP
}
},
methods: {
goBack() {
window.history.length > 1 ? this.$router.go(-1) : this.$router.push('/')
},
goToAboutPage() {
this.$router.push('/about');
}
}
}
Full Docs
Last updated
Was this helpful?