Introduction to and Installation of Vue Router
Route management is an indispensable part of frontend development when building modern Single Page Applications (SPAs). As the official routing manager maintained by the Vue.js team, Vue Router perfectly aligns with Vue's reactive data-driven philosophy. It is not merely a simple URL mapping tool but a fully-featured routing system that supports nested routes, dynamic routes, route guards, and fine-grained access control. By integrating Vue Router, developers can decouple page switching logic from business code, utilize the browser's native History API to achieve seamless page transitions without refreshing, and thereby provide a smooth user experience close to that of native applications. For beginners, understanding its core concepts is the cornerstone of mastering the Vue ecosystem; for advanced developers, it enables the construction of complex multi-level navigation architectures and refined access control strategies.
Quick Installation and Basic Configuration
The installation process for Vue Router is very intuitive and can typically be completed via npm or yarn package managers. In the root directory of your created Vue project, run the following command to introduce routing functionality:
npm install vue-router@latest
# Or use yarn
yarn add vue-router@latest
After installation, you need to initialize the router instance in the main entry file (usually main.js or src/main.ts). This step is crucial as it binds the router to the Vue application instance, ensuring that route states can respond in real-time to component changes.
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import Home from './views/Home.vue'
import About from './views/About.vue'
// Define route configuration
const routes = [
{
path: '/',
name: 'Home',
component: Home,
meta: { title: '首页' }
},
{
path: '/about',
name: 'About',
component: About,
meta: { title: '关于我们' }
}
]
// Create router instance
const router = createRouter({
history: createWebHistory(), // Use HTML5 mode, supports browser back button
routes
})
// Mount the router to the Vue application
app.use(router)
In the configuration above, createWebHistory provides an alternative based on URL Hash mode, but in modern development, it is recommended to use History mode for a better user experience. Additionally, the meta field in each route object is commonly used to store additional metadata, such as page titles or permission identifiers, which will play a role in subsequent route guards.
Core Concepts Explained: Navigation and Component Mapping
The core of Vue Router lies in establishing a dynamic mapping relationship between URL paths and Vue components. By defining the path attribute, we can precisely control which component is rendered when accessing a specific URL. For example, when a user visits /products/123, the system automatically matches the dynamic parameter route containing { id: 123 } and displays information about that ID in the corresponding component.
Besides static paths, Vue Router also supports various advanced features:
- Nested Routes: Allow defining child routes under a parent component to achieve modular page structures.
- Dynamic Routes: Utilize regular expressions or object parameters to match complex URL patterns.
- Route Meta Information: Add custom attributes to each route for easy global unified processing (e.g., setting page titles).
These features enable Vue Router to flexibly meet various scenario requirements, ranging from simple single-page displays to multi-level backend management systems.
Implementing Page Switching and Navigation Interaction
In actual development, users often need to trigger page jumps via buttons or links. Vue Router provides the router-link component and the $router.push() method to achieve this functionality. router-link is the recommended preferred choice in Vue 3, as it not only supports jumping but also handles parameterized routes through the to attribute and automatically processes browser forward/back button behaviors.
<!-- Use router-link for navigation -->
<router-link to="/about">About Us</router-link>
<router-link :to="{ name: 'Home', query: { page: 'home' } }">Go Home</router-link>
<!-- Use $router.push for dynamic jumping -->
<button @click="goToProfile">Go to Profile</button>
In App.vue or specific components, you can call the $router.push() method as follows:
import { useRouter } from 'vue-router'
export default defineComponent({
setup() {
const router = useRouter()
const goToProfile = () => {
// Jump with parameters
router.push('/user/456')
// Jump with query parameters
router.push('/search', { query: { keyword: 'vue' } })
// Replace current page (does not change URL)
router.replace('/new-page')
}
return { goToProfile }
}
})
Through the above methods, developers can flexibly control navigation behavior. Whether it is simple string jumps or complex object-based route configurations, they can be easily implemented. Meanwhile, router-link also supports attributes like active-class and exact-active-class to highlight currently active route links, enhancing interaction feedback.
Advanced Applications: Route Guards and Access Control
As applications become more complex, simple route jumping is no longer sufficient, making route guards (Route Guards) particularly important. Vue Router provides three key hook functions: beforeEnter, beforeEach, and beforeRouteUpdate, which allow us to intercept requests before page loading and execute unified logic judgments.
The most common application scenario is access control. Suppose we have a protected /admin route that can only be accessed by logged-in users. We can check the user's login status via the beforeEach hook:
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{
path: '/admin',
component: AdminPanel,
meta: { requiresAuth: true }
}
],
beforeEnter(to, from, next) {
// Check permission flag in route meta information
if (to.meta.requiresAuth) {
const isLoggedIn = checkLoginStatus() // Custom login status check function
if (!isLoggedIn) {
// Not logged in, redirect to login page
return next({ path: '/login', query: { redirect: to.fullPath } })
}
}
// Permission verification passed, continue entering the page
next()
}
})
In this example, the beforeEnter hook executes before the user attempts to access /admin. If a missing login status is detected, the system will automatically redirect the user to the /login page and save the original target address in the query parameters so that they can automatically jump back to the original page after logging in. This mechanism not only enhances security but also greatly simplifies repetitive permission judgment code within various components.
By mastering the installation, configuration, and core features of Vue Router, developers can quickly build single-page applications with clear structures, smooth interactions, and ease of maintenance, laying a solid foundation for further exploration into advanced topics such as Vuex/Pinia state management and Nuxt.js server-side rendering.