vue路由实现机制
Vue 路由实现机制
Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。其核心机制包括路由匹配、导航守卫、动态路由等。
路由匹配
Vue Router 通过路由配置表(routes)定义路径与组件的映射关系。当 URL 变化时,路由器会根据路径匹配对应的组件并渲染。
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
路由模式
Vue Router 支持两种路由模式:
- Hash 模式:利用 URL 的 hash(
#)模拟完整路径,兼容性高。const router = new VueRouter({ mode: 'hash' }) - History 模式:基于 HTML5 History API,路径更简洁,需服务器支持。
const router = new VueRouter({ mode: 'history' })
动态路由
通过冒号 : 定义动态路径参数,匹配到的值会注入组件的 $route.params。
{ path: '/user/:id', component: User }
导航守卫
导航守卫用于控制路由跳转,分为全局守卫、路由独享守卫和组件内守卫。
router.beforeEach((to, from, next) => {
// 全局前置守卫
next()
})
路由懒加载
通过动态导入实现按需加载组件,提升性能。
const User = () => import('./User.vue')
编程式导航
通过 $router 提供的 API 实现代码跳转。
this.$router.push('/home')
this.$router.replace('/login')
嵌套路由
通过 children 配置实现嵌套视图。
{
path: '/user',
component: User,
children: [
{ path: 'profile', component: Profile }
]
}
Vue Router 通过以上机制实现路由管理,支持灵活配置和扩展。







