vue路由实现机制
Vue 路由实现机制
Vue Router 是 Vue.js 的官方路由管理器,用于构建单页面应用(SPA)。其核心机制包括路由匹配、组件渲染和导航守卫等功能。
路由匹配
Vue Router 通过路由配置表(routes)定义路径与组件的映射关系。当 URL 变化时,路由器会根据路径匹配对应的路由配置,并确定需要渲染的组件。
const routes = [
{ path: '/home', component: Home },
{ path: '/about', component: About }
];
组件渲染
匹配到路由后,Vue Router 通过 <router-view> 动态渲染组件。<router-view> 是一个占位符,用于显示当前路由对应的组件内容。
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
导航守卫
导航守卫用于在路由跳转前后执行逻辑,例如权限验证或数据预加载。常见的守卫包括全局守卫、路由独享守卫和组件内守卫。
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login');
} else {
next();
}
});
动态路由
Vue Router 支持动态路由参数,通过冒号 : 标记动态片段。参数值会被解析到 $route.params 中。
const routes = [
{ path: '/user/:id', component: User }
];
编程式导航
除了声明式导航(<router-link>),Vue Router 提供了编程式导航方法,如 router.push 和 router.replace。
router.push('/home');
router.replace('/login');
路由模式
Vue Router 支持两种路由模式:
- Hash 模式:使用 URL 的 hash(
#)模拟完整路径,兼容性较好。 - History 模式:利用 HTML5 History API 实现无
#的 URL,需服务器配置支持。
const router = new VueRouter({
mode: 'history',
routes
});
懒加载
通过动态导入实现路由组件的懒加载,优化首屏加载性能。

const routes = [
{ path: '/home', component: () => import('./views/Home.vue') }
];






