vue文件实现页面跳转
使用 router-link 组件
在 Vue 文件中,可以通过 <router-link> 组件实现页面跳转。该组件是 Vue Router 提供的内置组件,用于声明式导航。
<template>
<router-link to="/target-path">跳转到目标页面</router-link>
</template>
to 属性指定目标路由路径,可以是字符串路径或路由对象。
编程式导航
通过 this.$router.push 方法可以在 JavaScript 中实现编程式导航。
methods: {
navigateToTarget() {
this.$router.push('/target-path');
}
}
也可以传递路由对象:
this.$router.push({ path: '/target-path' });
命名路由跳转
如果路由配置中定义了 name 属性,可以通过名称跳转。
this.$router.push({ name: 'targetRouteName' });
带参数跳转
传递参数到目标页面:
this.$router.push({
path: '/target-path',
query: { id: 123 } // 通过 URL 查询参数传递
});
// 或
this.$router.push({
name: 'targetRouteName',
params: { id: 123 } // 通过路由参数传递
});
替换当前路由
使用 replace 方法不会在历史记录中添加新条目:

this.$router.replace('/target-path');
前进后退导航
在路由历史中前进或后退:
this.$router.go(1); // 前进一步
this.$router.go(-1); // 后退一步
动态路由匹配
在路由配置中使用动态路径参数:
const routes = [
{ path: '/user/:id', component: User }
];
跳转时传递参数:
this.$router.push('/user/123');
在目标组件中通过 this.$route.params.id 获取参数值。

导航守卫
可以在跳转前后执行逻辑:
router.beforeEach((to, from, next) => {
// 跳转前逻辑
next();
});
懒加载路由
优化性能,按需加载路由组件:
const routes = [
{
path: '/target-path',
component: () => import('./views/TargetView.vue')
}
];
路由元信息
通过 meta 字段传递额外信息:
const routes = [
{
path: '/admin',
component: Admin,
meta: { requiresAuth: true }
}
];
在导航守卫中访问:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth) {
// 验证逻辑
}
next();
});






