Appearance
带参数的动态路由匹配
使用 路径参数
:
js
import User from './User.vue'
// 这些都会传递给 `createRouter`
const routes = [
// 动态字段以冒号开始
{ path: '/users/:id', component: User },
]
现在像 /users/johnny
和 /users/jolyne
这样的 URL 都会映射到同一个路由。
路径参数 用冒号 :
表示。当一个路由被匹配时,它的 params 的值将在每个组件中以 route.params
的形式暴露出来。因此,我们可以通过更新 User 的模板来呈现当前的用户 ID:
vue
<template>
<div>
<!-- 当前路由可以通过 $route 在模板中访问 -->
User {{ $route.params.id }}
</div>
</template>
响应路由参数的变化
要对同一个组件中参数的变化做出响应的话,你可以简单地 watch $route
对象上的任意属性,在这个场景中,就是 $route.params
:
vue
<script setup>
import { watch } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
watch(() => route.params.id, (newId, oldId) => {
// 对路由变化做出响应...
})
</script>
vue
<script>
export default {
created() {
this.$watch(
() => this.$route.params.id,
(newId, oldId) => {
// 对路由变化做出响应...
}
)
},
}
</script>
捕获所有路由或 404 Not found 路由
如果我们想匹配任意路径,我们可以使用自定义的 路径参数 正则表达式,在 路径参数 后面的括号中加入 正则表达式 :
js
const routes = [
// 将匹配所有内容并将其放在 `route.params.pathMatch` 下
{ path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound },
// 将匹配以 `/user-` 开头的所有内容,并将其放在 `route.params.afterUser` 下
{ path: '/user-:afterUser(.*)', component: UserGeneric },
]
RouterLink上传参
vue
<template>
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
</template>
这需要确保路由具有 name
属性:
js
const routes = [
{
path: '/user/:userId',
name: 'user',
component: User,
},
]