Routing
Routing is essential for building single-page applications (SPAs) with multiple views. Vue Router is the official routing library for Vue.js, providing seamless integration with Vue’s component system.What is Routing?
In a traditional multi-page application, the server determines which HTML page to send based on the URL. In a single-page application, JavaScript handles navigation by:- Intercepting link clicks
- Updating the URL without a page reload
- Rendering the appropriate component based on the current URL
Vue Router
Vue Router is the official router for Vue.js. It deeply integrates with Vue’s core to make building SPAs a breeze.Installation
Basic Setup
Router View
The<router-view> component renders the matched component for the current route:
Route Configuration
Named Routes
Give routes a name for easier navigation:Nested Routes
Nest routes to create complex UI structures:Dynamic Route Matching
Capture URL parameters:Catch-All Routes
Handle 404 pages:Navigation
Declarative Navigation
Using<router-link>:
Programmatic Navigation
Using the router instance:Navigation Methods
router.push()- Navigate to a new routerouter.replace()- Navigate without adding history entryrouter.go(n)- Navigate forward or backward in historyrouter.back()- Go back one steprouter.forward()- Go forward one step
Route Guards
Global Guards
Execute logic before every navigation:Per-Route Guards
Define guards in route configuration:In-Component Guards
Define guards within components:Route Meta Fields
Attach custom metadata to routes:History Modes
HTML5 History Mode
Uses the History API for clean URLs:Hash Mode
Uses URL hash for routing (no server configuration needed):Memory Mode
For server-side rendering or testing:Lazy Loading Routes
Load routes on demand for better performance:Named Chunks
Group related routes:Advanced Features
Scroll Behavior
Customize scroll position on navigation:Route Transitions
Animate route changes:Data Fetching
Fetch data before or after navigation:Multiple Router Views
Render multiple components simultaneously:Testing
Mocking the Router
Best Practices
- Use lazy loading for large applications to reduce initial bundle size
- Define route names for easier refactoring and type safety
- Utilize route guards for authentication and authorization
- Keep route configuration organized by splitting into modules for large apps
- Use route meta fields for common route properties
- Handle 404 errors with catch-all routes
- Configure server properly when using HTML5 history mode