useRoute
useRoute 可组合函数返回当前路由。
在 Vue 组件的模板中,你可以使用
$route
访问路由。示例
¥Example
在以下示例中,我们通过 useFetch
调用一个 API,并使用动态页面参数。 - slug
- 作为 URL 的一部分。
¥In the following example, we call an API via useFetch
using a dynamic page parameter - slug
- as part of the URL.
~/pages/[slug].vue
<script setup lang="ts">
const route = useRoute()
const { data: mountain } = await useFetch(`/api/mountains/${route.params.slug}`)
</script>
<template>
<div>
<h1>{{ mountain.title }}</h1>
<p>{{ mountain.description }}</p>
</div>
</template>
如果你需要访问路由查询参数(例如路径 /test?example=true
中的 example
),则可以使用 useRoute().query
而不是 useRoute().params
。
¥If you need to access the route query parameters (for example example
in the path /test?example=true
), then you can use useRoute().query
instead of useRoute().params
.
API
除了动态参数和查询参数外,useRoute()
还提供与当前路由相关的以下计算引用:
¥Apart from dynamic parameters and query parameters, useRoute()
also provides the following computed references related to the current route:
fullPath
:与当前路由关联的编码 URL,包含路径、查询和哈希值hash
:URL 中以 # 开头的解码哈希值部分query
:访问路由查询参数matched
:包含当前路由位置的规范化匹配路由数组meta
:附加到记录的自定义数据name
:路由记录的唯一名称path
:URL 的编码路径名部分redirectedFrom
:在到达当前路由位置之前尝试访问的路由位置