面试题:Vue Router 中 route 和 router 有哪些区别?

在 Vue Router 中,route 和 router 是两个非常重要的对象,但它们的作用和用途完全不同。以下是它们的区别:


1. route

  • 定义route 是一个表示当前路由信息的对象,包含了当前激活路由的状态信息。
  • 获取方式:在组件中通过 this.$route 访问。
  • 作用:用于获取当前路由的详细信息,比如路径、参数、查询字符串等。
  • 常用属性
    • path:当前路由的路径(如 /user/123)。
    • params:动态路由参数(如 { id: '123' })。
    • query:查询参数(如 { name: 'John' })。
    • hash:URL 中的 hash 值(如 #section)。
    • fullPath:完整的 URL 路径(如 /user/123?name=John#section)。
    • matched:当前路由匹配的所有路由记录(数组形式)。
    • name:当前路由的名称(如果定义了路由名称)。
  • 示例
    // 获取当前路由的动态参数
    const userId = this.$route.params.id;
    // 获取查询参数
    const userName = this.$route.query.name;
    // 获取当前路由的动态参数
    const userId = this.$route.params.id;
    
    // 获取查询参数
    const userName = this.$route.query.name;
    // 获取当前路由的动态参数 const userId = this.$route.params.id; // 获取查询参数 const userName = this.$route.query.name;

2. router

  • 定义router 是 Vue Router 的实例,用于控制路由的跳转、导航守卫等操作。
  • 获取方式:在组件中通过 this.$router 访问。
  • 作用:用于编程式导航、路由跳转、导航守卫等。
  • 常用方法
    • push:跳转到指定路由(会向 history 栈中添加一条记录)。
    • replace:跳转到指定路由(不会向 history 栈中添加记录,替换当前记录)。
    • go:在 history 记录中前进或后退。
    • back:后退一步。
    • forward:前进一步。
    • beforeEachbeforeResolveafterEach:全局导航守卫。

3. 区别总结

特性routerouter
作用表示当前路由的状态信息控制路由的跳转和导航行为
获取方式this.$routethis.$router
常用属性/方法pathparamsqueryhash 等pushreplacegoback 等
使用场景获取当前路由的详细信息编程式导航、路由跳转、导航守卫

4. 示例对比

// 获取当前路由的动态参数(使用 route)
const userId = this.$route.params.id;
// 跳转到新路由(使用 router)
this.$router.push({ path: `/user/${userId}`, query: { name: 'John' } });
// 获取当前路由的动态参数(使用 route)
const userId = this.$route.params.id;

// 跳转到新路由(使用 router)
this.$router.push({ path: `/user/${userId}`, query: { name: 'John' } });
// 获取当前路由的动态参数(使用 route) const userId = this.$route.params.id; // 跳转到新路由(使用 router) this.$router.push({ path: `/user/${userId}`, query: { name: 'John' } });

5. 总结

  • route:用于获取当前路由的状态信息,是只读的。
  • router:用于控制路由的跳转和导航行为,是可操作的。
  • 两者通常配合使用,route 用于获取信息,router 用于执行操作。
THE END
点赞12 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容