vue中实现路由跳转
Vue 中实现路由跳转的方法
使用 <router-link> 组件
在模板中直接使用 <router-link> 组件实现导航,适合声明式跳转。通过 to 属性指定目标路由路径或命名路由:
<router-link to="/home">跳转到首页</router-link>
<router-link :to="{ name: 'user', params: { id: 123 }}">用户页</router-link>
编程式导航
通过 this.$router 提供的 API 实现跳转,适合在逻辑代码中动态控制路由:
// 跳转到指定路径
this.$router.push('/home');
// 跳转到命名路由并传参
this.$router.push({ name: 'user', params: { id: 1 } });
// 带查询参数
this.$router.push({ path: '/search', query: { keyword: 'vue' } });
// 替换当前路由(无历史记录)
this.$router.replace('/login');
路由传参方式
- params:需在路由配置中定义参数(
path: '/user/:id'),通过$route.params获取 - query:无需预定义,通过
$route.query获取(如?key=value) - props:在路由配置中设置
props: true可将 params 转为组件的 props
导航守卫控制跳转
可在全局或组件内通过守卫拦截或重定向路由:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login');
} else {
next();
}
});
动态路由匹配
路由配置中使用冒号标记动态路径参数,实现灵活匹配:
const routes = [
{ path: '/user/:id', component: User }
];
路由懒加载
通过动态导入实现路由组件按需加载:
const User = () => import('./views/User.vue');
注意事项
- 路由跳转前可通过
this.$router.resolve()解析目标路由信息 - 使用
router.go(n)可在历史记录中前进或后退 - Hash 模式与 History 模式的跳转行为一致,但 URL 表现形式不同







