在 Vue 项目中,如果使用了 Vue Router,可以通过以下几种方式在组件中获取当前的路由信息(如路径、参数、查询字符串等)。
一、在 Vue 2 + Vue Router 中获取路由信息
1. 通过 this.$route
对象(选项式 API)
Vue Router 会自动将当前路由信息注入每个组件的 this.$route
中。
<script>
export default {
mounted() {
// 获取路由信息
console.log('当前路径:', this.$route.path); // '/user/123'
console.log('路由参数:', this.$route.params); // { id: '123' }
console.log('查询参数:', this.$route.query); // { tab: 'profile' }
console.log('路由名称:', this.$route.name); // 'UserProfile'
console.log('匹配的路由记录:', this.$route.matched); // 路由记录数组
console.log('哈希值:', this.$route.hash); // '#section1'
},
watch: {
// 监听路由变化(如参数变化)
'$route'(to, from) {
console.log('路由变化:', from.path, '→', to.path);
this.fetchUserData(to.params.id);
}
},
methods: {
fetchUserData(id) {
// 根据路由参数加载数据
}
}
}
</script>
2. 在模板中直接使用 $route
<template>
<div>
<h1>当前路径: {{ $route.path }}</h1>
<p>用户ID: {{ $route.params.id }}</p>
<p>标签页: {{ $route.query.tab }}</p>
</div>
</template>
二、在 Vue 3 + Composition API 中获取路由信息
推荐使用 Vue Router 提供的 组合式 API 函数。
1. 使用 useRoute()
获取路由信息
<script setup>
import { useRoute } from 'vue-router'
import { watch } from 'vue'
// 获取当前路由对象
const route = useRoute()
// 直接使用
console.log('路径:', route.path)
console.log('参数:', route.params.id)
console.log('查询:', route.query.tab)
// 监听路由变化
watch(
() => route.params.id,
(newId, oldId) => {
console.log('用户ID变化:', oldId, '→', newId)
fetchUserData(newId)
}
)
function fetchUserData(id) {
// 加载数据
}
</script>
<template>
<div>
<h1>用户详情 (ID: {{ route.params.id }})</h1>
<p>查询参数: {{ route.query.tab }}</p>
</div>
</template>
✅
useRoute()
返回的是一个响应式对象,但不要解构它:const { params, query } = route // ❌ 错误:失去响应性 const route = useRoute() // ✅ 正确
2. 使用 useRouter()
获取路由实例(可选)
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
// 可调用 router.push(), router.replace() 等
三、通过 props
接收路由参数(推荐用于路由组件)
可以将路由参数以 props
形式传递给组件,提升组件的可复用性和可测试性。
1. 启用 props
模式
// router/index.js
const routes = [
{
path: '/user/:id',
component: UserProfile,
props: true // 将 route.params 映射为组件的 props
}
]
2. 组件中接收 props
<!-- UserProfile.vue -->
<script setup>
// id 来自路由参数 :id
const props = defineProps({
id: {
type: String,
required: true
}
})
console.log('用户ID:', props.id)
</script>
✅ 优点:组件不依赖
$route
,更容易单元测试。
四、监听路由变化的注意事项
- 使用
watch
监听$route
或route.params
,而不是在mounted
中只获取一次。 - 对于路由参数变化但组件复用的场景(如
/user/1
→/user/2
),必须监听$route
才能响应变化。
总结:获取路由信息的方式
场景 | 推荐方式 |
---|---|
Vue 2 / 选项式 API | this.$route |
Vue 3 / 组合式 API | useRoute() |
模板中直接使用 | {{ $route.path }} (Vue 2)或 {{ route.path }} (Vue 3) |
提升组件复用性 | 使用 props: true 将参数传递给组件 |
监听路由变化 | watch('$route') (Vue 2)或 watch(() => route.params) (Vue 3) |
✅ 最佳实践:
- 在 Vue 3 项目中,优先使用
useRoute()
。- 对于仅依赖路由参数的组件,使用
props
模式解耦。- 避免在模板中过度使用
$route
,保持逻辑清晰。
THE END