vue路由实现介绍
Vue 路由基础概念
Vue Router 是 Vue.js 的官方路由管理器,用于构建单页面应用(SPA)。它通过动态映射组件到路由实现页面无刷新跳转,同时支持嵌套路由、路由参数、导航守卫等高级功能。
安装与基本配置
通过 npm 或 yarn 安装 Vue Router:
npm install vue-router@4
在项目中初始化路由:
import { createRouter, createWebHistory } from 'vue-router';
import Home from './views/Home.vue';
import About from './views/About.vue';
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
});
在 main.js 中注入路由实例:
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
createApp(App).use(router).mount('#app');
路由视图与导航
在组件模板中使用 <router-view> 作为路由组件渲染出口:
<template>
<div>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<router-view></router-view>
</div>
</template>
<router-link> 生成导航链接,to 属性指定目标路径。通过 router.push 编程式导航:
methods: {
navigate() {
this.$router.push('/about');
}
}
动态路由与参数
通过冒号 : 定义动态路径参数:

routes: [
{ path: '/user/:id', component: User }
]
在组件中通过 $route.params 访问参数:
const userId = this.$route.params.id;
使用 props 解耦路由参数:
routes: [
{ path: '/user/:id', component: User, props: true }
]
组件通过 props 接收参数:
export default {
props: ['id']
};
嵌套路由
通过 children 配置嵌套路由:

routes: [
{
path: '/user',
component: User,
children: [
{ path: 'profile', component: Profile },
{ path: 'posts', component: Posts }
]
}
]
父组件需包含 <router-view> 渲染子路由:
<template>
<div>
<h2>User Page</h2>
<router-view></router-view>
</div>
</template>
导航守卫
全局前置守卫 beforeEach 用于权限控制:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login');
} else {
next();
}
});
路由独享守卫 beforeEnter:
routes: [
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => {
// 逻辑处理
}
}
]
组件内守卫(如 beforeRouteEnter):
export default {
beforeRouteEnter(to, from, next) {
// 无法访问 `this`,可通过回调获取组件实例
next(vm => {
console.log(vm);
});
}
};
路由懒加载
通过动态导入实现懒加载,提升性能:
routes: [
{
path: '/dashboard',
component: () => import('./views/Dashboard.vue')
}
]
路由模式
- Hash 模式:使用 URL 哈希(
#),兼容性好:createWebHashHistory() - History 模式:依赖服务器配置,需处理 404 回退:
createWebHistory()
以上内容覆盖了 Vue Router 的核心功能,可根据实际需求选择合适的功能组合。






