- 在 Vue 中,
this.$route和this.$router是与 Vue Router 相关的两个重要对象,它们在不同场景下有不同的用途:
使用 this.$route 的情况
-
获取路由信息
- 获取当前路由的路径:
this.$route.path可以获取当前路由的完整路径,例如/home、/user/profile等。 - 获取路由参数:
this.$route.params用于获取动态路由参数。例如,对于路由/user/:id,如果当前路径是/user/123,则this.$route.params.id的值为123。 - 获取查询参数:
this.$route.query用于获取 URL 中的查询参数。例如,对于路径/search?keyword=vue,this.$route.query.keyword的值为vue。 - 获取路由名称:
this.$route.name可以获取当前路由的名称,这在路由守卫和动态路由匹配中非常有用。
- 获取当前路由的路径:
-
在模板中使用
- 绑定数据:可以在模板中使用
this.$route的属性来绑定数据。例如,显示当前路由的路径或参数:<template> <div> <p>当前路径: {{ $route.path }}</p> <p>用户 ID: {{ $route.params.id }}</p> </div> </template>
- 绑定数据:可以在模板中使用
-
路由守卫中使用
- 导航守卫:在路由守卫(如
beforeEach、beforeEnter等)中,this.$route可以用来获取当前路由的信息,以便进行权限验证、数据预加载等操作。router.beforeEach((to, from, next) => { if (to.path === '/admin' && !isAuthenticated) { next('/login'); } else { next(); } });
- 导航守卫:在路由守卫(如
使用 this.$router 的情况
-
导航操作
- 跳转到新路由:
this.$router.push用于导航到新的路由。例如,跳转到/home:this.$router.push('/home'); - 替换当前路由:
this.$router.replace用于替换当前路由,不会向历史记录添加新记录。例如,替换当前路由为/login:this.$router.replace('/login'); - 后退和前进:
this.$router.go用于在历史记录中前进或后退。例如,后退一步:this.$router.go(-1);
- 跳转到新路由:
-
添加或移除路由
- 动态添加路由:
this.$router.addRoutes用于动态添加新的路由规则。虽然在 Vue Router 4.x 中已经不推荐使用addRoutes,但在某些情况下仍然可以使用。this.$router.addRoutes([ { path: '/new-route', component: NewRouteComponent } ]);
- 动态添加路由:
-
获取路由实例
- 在组件外部使用:在组件外部(如 Vuex 动作中)需要使用路由实例时,可以通过
this.$router获取。例如,在 Vuex 动作中跳转路由:// store.js actions: { login({ commit }) { // 模拟登录逻辑 commit('setAuthenticated', true); this.$router.push('/home'); } }
- 在组件外部使用:在组件外部(如 Vuex 动作中)需要使用路由实例时,可以通过
总结
this.$route主要用于获取当前路由的信息,如路径、参数、查询字符串等。this.$router主要用于进行路由导航操作,如跳转、替换、前进和后退等。
在实际开发中,根据具体需求选择合适的对象来使用。