Vue-Router 第二节:动态路由
1、动态路由
在日常开发中,我们某一组的用户(ID不同)要看到同一个组件,例如技术部要看到相关技术部的文档页面,这时我们可以用到动态路由 ;在路由配置时 使用一个动态字段来实现。称之为路径参数。
创建组件:user
下面我们来添加一个/user/...的动态路由。

javascript
// router/index.ts页面
const routes: Array<RouteRecordRaw> = [
// 可直接导入或者引入
{
path: '/',
component: () => import("@/views/home/index.vue"),
},
{
path: '/about',
component: About
},
{ // 动态字段以:开始 这里就是id
path: '/user/:id',
component: import("@/views/user/index.vue")
}
]
像user/101
,user/102
等这些url都会进入这个路由组件中。以下模拟下:
xml
// APP.vue页面
<template>
<div>
<router-link to="/about">go About</router-link>
<br>
<router-link to="/">go Home</router-link>
<br>
<router-link to="/user/A">模拟A进入技术部</router-link>
<br>
<router-link to="/user/B">模拟B进入技术部</router-link>
<router-view />
</div>
</template>
<script setup lang="ts">
</script>
<style scoped></style>

2、动态路由参数的变化
点击这两个路由都可以进入我们的user 组件中。在我们user 组件中可以通过$route.params
来获取我们传的参数。在这种使用情况下,组件重复使用肯定是比卸载再创建高效多,所以此组件的生命周期是无效的,我们要监听其参数的变化,就可以来监听$route.params
3、匹配404Not found 路由
在我们上面我们匹配的路由都是/user
当我们想匹配所有路径的路由,使用正则表达式来匹配URL。
javascript
// router/index.ts页面
const routes: Array<RouteRecordRaw> = [
// 可直接导入或者引入
{
path: '/',
component: () => import("@/views/home/index.vue"),
},
{
path: '/about',
component: About
},
{
path: '/user/:id',
component: import("@/views/user/index.vue")
},
{
path: '/:pages(.*)*', // 使用正则表达式来匹配URL (.*)表示可以匹配任何数量的任何字符 *表示前面的元素(.*)可以出现零次或多次
component: import("@/views/notFont/index.vue")
}
]
ini
// 模拟任意url
<router-link to="/not/page/notfont">进入其他不知名页面</router-link>
