动态路径参数
- router 配置 「/user/:id」:/user/foo 和 /user/bar 都将映射到相同的路由 User;
const router = new VueRouter({ routes: [{ path: '/user/:id', // 动态路径参数 以冒号开头 props: true, // 开启 props,会把 URL 中的参数传递给组件 component: () => import('@/User.vue'), // 懒加载组件 },] })
- 获取参数
<template> <div> <!-- 方式1: 通过当前路由规则,获取数据 --> 通过当前路由规则获取:{{ $route.params.id }} <br> <!-- 方式2(推荐):路由规则中开启 props 传参 --> 通过开启 props 获取:{{ id }} </div> </template> <script> export default { name: 'User', props: ['id'] } </script>
- 设置多段"路径参数":
模式 匹配路径 $route.params /user/:username /user/evan { username: ‘evan’ } /user/:username/post/:post_id /user/evan/post/123 { username: ‘evan’, post_id: ‘123’ }
监控路由参数的变化
-
当使用路由参数时,例如从 /user/foo 导航到 /user/bar,User 组件实例会被复用,因为两个路由都渲染同个组件 User,比起销毁再创建,复用则显得更加高效,这也意味着 User 组件的生命周期钩子不会再被调用;
-
检测路由参数变化:
export default { // 第一种:使用 watch (监测变化) $route 对象 watch: { $route(to, from) { // 对路由变化作出响应... } }, // 第二种:使用 2.2 中引入的 beforeRouteUpdate 导航守卫 beforeRouteUpdate(to, from, next) { // don't forget to call next() } }
捕获所有路由或 404 Not found 路由
-
匹配任意路径,使用通配符 (*)
{ // 会匹配所有路径,应该放在最后 // 通常用于客户端 404 错误 path: '*' } { // 会匹配以 `/user-` 开头的任意路径 path: '/user-*' }
-
pathMatch 获取通配符参数
// 给出一个路由 { path: '/user-*' } this.$router.push('/user-admin') this.$route.params.pathMatch // 'admin' // 给出一个路由 { path: '*' } this.$router.push('/non-existing') this.$route.params.pathMatch // '/non-existing'
匹配优先级
同一个路径可以匹配多个路由,路由定义得越早,优先级就越高
webpack 核心功能👉 plugins 插件机制
上一篇