杨斌
发布于 2025-06-29 / 11 阅读
0
0

Vue3中useRoute与useRouter的区别

在 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 })

核心区别总结

特性

useRoute()

useRouter()

返回值类型

响应式路由信息对象 (只读)

Router 实例 (非响应式)

主要用途

读取当前路由信息(参数/查询/路径等)

编程式导航(跳转/后退/动态路由管理等)

是否响应式

✅ 是(可监听变化)

❌ 否(实例方法不会变)

类比关系

类似 this.$route (Options API)

类似 this.$router (Options API)


使用示例对比

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()


评论