Vue路由中 $router 和 $route 两个对象的辨析

502 阅读1分钟
  • 在 Vue 中,this.$routethis.$router 是与 Vue Router 相关的两个重要对象,它们在不同场景下有不同的用途:

使用 this.$route 的情况

  1. 获取路由信息

    • 获取当前路由的路径this.$route.path 可以获取当前路由的完整路径,例如 /home/user/profile 等。
    • 获取路由参数this.$route.params 用于获取动态路由参数。例如,对于路由 /user/:id,如果当前路径是 /user/123,则 this.$route.params.id 的值为 123
    • 获取查询参数this.$route.query 用于获取 URL 中的查询参数。例如,对于路径 /search?keyword=vuethis.$route.query.keyword 的值为 vue
    • 获取路由名称this.$route.name 可以获取当前路由的名称,这在路由守卫和动态路由匹配中非常有用。
  2. 在模板中使用

    • 绑定数据:可以在模板中使用 this.$route 的属性来绑定数据。例如,显示当前路由的路径或参数:
      <template>
        <div>
          <p>当前路径: {{ $route.path }}</p>
          <p>用户 ID: {{ $route.params.id }}</p>
        </div>
      </template>
      
  3. 路由守卫中使用

    • 导航守卫:在路由守卫(如 beforeEachbeforeEnter 等)中,this.$route 可以用来获取当前路由的信息,以便进行权限验证、数据预加载等操作。
      router.beforeEach((to, from, next) => {
        if (to.path === '/admin' && !isAuthenticated) {
          next('/login');
        } else {
          next();
        }
      });
      

使用 this.$router 的情况

  1. 导航操作

    • 跳转到新路由this.$router.push 用于导航到新的路由。例如,跳转到 /home
      this.$router.push('/home');
      
    • 替换当前路由this.$router.replace 用于替换当前路由,不会向历史记录添加新记录。例如,替换当前路由为 /login
      this.$router.replace('/login');
      
    • 后退和前进this.$router.go 用于在历史记录中前进或后退。例如,后退一步:
      this.$router.go(-1);
      
  2. 添加或移除路由

    • 动态添加路由this.$router.addRoutes 用于动态添加新的路由规则。虽然在 Vue Router 4.x 中已经不推荐使用 addRoutes,但在某些情况下仍然可以使用。
      this.$router.addRoutes([
        { path: '/new-route', component: NewRouteComponent }
      ]);
      
  3. 获取路由实例

    • 在组件外部使用:在组件外部(如 Vuex 动作中)需要使用路由实例时,可以通过 this.$router 获取。例如,在 Vuex 动作中跳转路由:
      // store.js
      actions: {
        login({ commit }) {
          // 模拟登录逻辑
          commit('setAuthenticated', true);
          this.$router.push('/home');
        }
      }
      

总结

  • this.$route 主要用于获取当前路由的信息,如路径、参数、查询字符串等。
  • this.$router 主要用于进行路由导航操作,如跳转、替换、前进和后退等。

在实际开发中,根据具体需求选择合适的对象来使用。