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.
./router/index.js
constroutes= [{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.
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.
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
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.
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.