vue实现路由匹配
路由匹配的基本概念
在Vue中,路由匹配通常由Vue Router实现,通过定义路由规则将URL路径映射到对应的组件。核心是通过配置routes数组,定义路径(path)和组件(component)的对应关系。
静态路由匹配
静态路由是最简单的匹配方式,直接指定路径与组件的映射关系:
const routes = [
{ path: '/home', component: Home },
{ path: '/about', component: About }
];
当访问/home时,渲染Home组件;访问/about时,渲染About组件。
动态路由匹配
动态路由通过冒号(:)标记路径参数,匹配变化的URL片段:
const routes = [
{ path: '/user/:id', component: User }
];
访问/user/123时,id参数值为123,可在组件内通过this.$route.params.id获取。
嵌套路由匹配
通过children属性实现嵌套路由,适合有层级结构的页面:

const routes = [
{
path: '/dashboard',
component: Dashboard,
children: [
{ path: 'profile', component: Profile },
{ path: 'settings', component: Settings }
]
}
];
访问/dashboard/profile时,Dashboard组件内会嵌套渲染Profile组件。
通配符与404路由
使用通配符(*)匹配未定义的路径,通常用于404页面:
const routes = [
{ path: '*', component: NotFound }
];
当访问未配置的路径时,渲染NotFound组件。

路由优先级规则
Vue Router按照路由定义的顺序匹配,先定义的路由优先级更高。动态路由和静态路由混合时,静态路由优先匹配。例如:
const routes = [
{ path: '/user/me', component: Me }, // 优先匹配
{ path: '/user/:id', component: User }
];
编程式导航匹配
通过this.$router.push或<router-link>触发路由跳转时,路径需与定义的路由规则一致:
this.$router.push('/user/123'); // 匹配动态路由
this.$router.push({ name: 'user', params: { id: 123 } }); // 命名路由方式
路由守卫控制匹配
通过beforeEach等守卫函数,可在路由匹配前后进行逻辑控制:
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// 检查权限逻辑
} else {
next();
}
});
命名路由简化匹配
为路由定义name属性,可通过名称而非路径跳转,避免硬编码:
const routes = [
{ path: '/user/:id', name: 'user', component: User }
];
// 跳转时
this.$router.push({ name: 'user', params: { id: 123 } });






