vue实现路由匹配
Vue 路由匹配实现方法
在 Vue 中实现路由匹配通常使用 Vue Router 库。以下是核心实现方式:
基础路由配置
安装 Vue Router 后,在路由配置文件中定义路径与组件的映射关系:
import { createRouter, createWebHistory } from 'vue-router'
import Home from './views/Home.vue'
import User from './views/User.vue'
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/user/:id', component: User }
]
})
动态路由匹配
通过冒号 : 标记动态路径参数:
routes: [
{ path: '/user/:username/post/:postId', component: UserPost }
]
路由参数获取
在组件中通过 useRoute 访问当前路由信息:
import { useRoute } from 'vue-router'
export default {
setup() {
const route = useRoute()
console.log(route.params.username) // 获取动态参数
}
}
嵌套路由配置
使用 children 属性实现嵌套视图:
routes: [
{
path: '/user/:id',
component: User,
children: [
{ path: 'profile', component: Profile },
{ path: 'posts', component: Posts }
]
}
]
路由匹配语法
Vue Router 4.x 支持高级匹配模式:
- 自定义正则:
path: '/user/:id(\\d+)'(只匹配数字ID) - 可选参数:
path: '/user/:id?' - 多段参数:
path: '/user/:id+/posts'
导航守卫
通过守卫控制路由匹配行为:
router.beforeEach((to, from) => {
if (to.meta.requiresAuth) {
return { path: '/login' }
}
})
路由别名
为同一组件设置多个路径:
{ path: '/home', component: Home, alias: ['/', '/welcome'] }
404 路由处理
捕获未匹配路由:
{ path: '/:pathMatch(.*)*', component: NotFound }
编程式导航
通过代码控制路由跳转:
import { useRouter } from 'vue-router'
const router = useRouter()
router.push('/user/123') // 跳转到指定路径
以上方法组合使用可以满足大多数路由匹配需求,根据实际场景选择合适的方式实现。







