在 Vue 3 的 Composition API 中(配合 Vue Router 4),useRoute()
和 useRouter()
都是用于路由管理的函数,但它们的用途和返回值有本质区别:
const route = useRoute()
作用:获取当前激活的路由信息对象(响应式)
返回值:一个包含当前路由详细信息的响应式对象
包含的关键属性:
{
path: '/user/123', // 当前路径
params: { id: '123' }, // 动态路由参数
query: { name: 'John' }, // URL 查询参数
hash: '#profile', // URL 哈希值
fullPath: '/user/123?name=John#profile', // 完整 URL
name: 'user-profile', // 路由名称(如果有)
matched: [...] // 匹配的路由记录数组
}
典型使用场景:
// 获取动态路由参数
const userId = computed(() => route.params.id)
// 获取查询参数
const searchKeyword = computed(() => route.query.keyword)
// 监听路由变化
watch(() => route.params.id, (newId) => {
fetchUserData(newId)
})
const router = useRouter()
作用:获取 Router 实例(用于编程式导航)
返回值:Vue Router 的实例对象(非响应式)
包含的关键方法:
router.push('/home') // 导航到新页面(添加历史记录)
router.replace('/login') // 替换当前页面(无历史记录)
router.go(-1) // 后退一页
router.back() // 等同于 go(-1)
router.forward() // 等同于 go(1)
router.resolve(...) // 解析路由路径
router.addRoute(...) // 动态添加路由
典型使用场景:
// 跳转到新页面
function goToUserPage(id) {
router.push(`/user/${id}`)
}
// 替换当前页面
function forceLogin() {
router.replace('/login')
}
// 动态添加路由
router.addRoute({ path: '/admin', component: AdminPage })
核心区别总结
使用示例对比
import { useRoute, useRouter } from 'vue-router'
export default {
setup() {
const route = useRoute()
const router = useRouter()
// 读取路由参数
const userId = route.params.id
// 编程式导航
const goHome = () => router.push('/')
return { userId, goHome }
}
}
💡 黄金法则:
需要获取 URL 参数/路径/查询 → 用
useRoute()
需要跳转页面/管理路由 → 用
useRouter()