接着vue06来看
带参数的动态路由匹配
很多时候,我们需要将给定匹配模式的路由映射到同一个组件。例如,我们可能有一个 User
组件,它应该对所有用户进行渲染,但用户 ID 不同。在 Vue Router 中,我们可以在路径中使用一个动态字段来实现,我们称之为 路径参数 :
1.将index.js中A的path改为/a/:id
//将路径与组件进行关联
import { createRouter, createWebHistory } from 'vue-router';
import A from '../routeComponents/A.vue';
import B from '../routeComponents/B.vue';
import C from '../routeComponents/C.vue';
//创建路由实例并传递 `routes` 配置
// 你可以在这里输入更多的配置,但我们在这里
// 暂时保持简单
const router = createRouter({
history: createWebHistory(),
// 将每个路由映射到对应组件
routes: [
// 动态字段以冒号开始
{
path: '/a/:id', //动态参数
component: A //组件
},
{
path: '/b',
component: B
},
{
path: '/c',
component: C
}
],
});
export default router;
2.将index.vue中A的path改为/a/s001
<script></script>
<template>
<div class="route">
<ul>
<!--使用 router-link 组件进行导航 -->
<!--通过传递 `to` 来指定链接 -->
<!--`<router-link>` 将呈现一个带有正确 `href` 属性的 `<a>` 标签-->
<router-link to="/a/s001">
<li>A</li>
</router-link>
<router-link to="/b">
<li>B</li>
</router-link>
<router-link to="/c">
<li>C</li>
</router-link>
</ul>
<div class="tabBox">
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
</div>
</div>
</template>
<style scoped>
div.route {
width: 50%;
}
div.route div.tabBox{
background-color: red;
height: 80px;
margin-top: 50px;
text-align: center;
}
div.route ul {
display: flex;
justify-content: space-around;
width: 100%;
list-style: none;
}
div.route ul li {
width: 200px;
height: 80px;
background-color: blueviolet;
display: flex;
align-items: center;
justify-content: center;
}
</style>
结果如下图所示:
点A时,导航栏会显示
3.路径参数 用冒号 :
表示。当一个路由被匹配时,它的 params 的值将在每个组件中以 this.$route.params
的形式暴露出来。因此,我们可以通过更新 a的模板来呈现当前的用户 ID:
给A.vue中加入{{this.$route.params
}}
<script></script>
<template>
<div class="tabBox">
<!-- 当一个路由被匹配时,路由的 params 的值将在每个组件中以 this.$route.params 的形式暴露出来 -->
A
{{ this.$route.params }}
</div>
</template>
<style></style>
点A后,结果如下图所示:
或 给A.vue中加入{{this.$route.params.id
}}
<script></script>
<template>
<div class="tabBox">
<!-- 当一个路由被匹配时,路由的 params 的值将在每个组件中以 this.$route.params 的形式暴露出来 -->
A
{{ this.$route.params.id }}
</div>
</template>
<style></style>
点A后,结果如下图所示:
给B.vue中加入{{this.$route.params.username
}}
<script></script>
<template>
<div class="tabBox">
B
{{ this.$route.params.username }}
</div>
</template>
<style></style>
点B后,结果如下图所示:
给B.vue中加入{{this.$route.params
}}
<script></script>
<template>
<div class="tabBox">
B
{{ this.$route.params}}
</div>
</template>
<style></style>
点B后,结果如下图所示: