vue实现导航跳转
vue实现导航跳转的方法
使用 <router-link> 组件
在 Vue 中,可以通过 <router-link> 组件实现导航跳转。这种方式适用于模板中直接声明式导航。
<router-link to="/home">首页</router-link>
<router-link :to="{ name: 'user', params: { userId: 123 }}">用户页</router-link>
to 属性可以是一个字符串路径,也可以是一个包含路由名称或参数的对象。
编程式导航
通过 this.$router.push 方法可以在 JavaScript 中实现编程式导航。
// 跳转到指定路径
this.$router.push('/home');
// 跳转到命名路由
this.$router.push({ name: 'user', params: { userId: 123 } });
// 带查询参数
this.$router.push({ path: '/search', query: { keyword: 'vue' } });
替换当前路由
使用 this.$router.replace 方法可以替换当前路由,不会在历史记录中留下痕迹。
this.$router.replace('/login');
前进或后退
通过 this.$router.go 方法可以在历史记录中前进或后退。
// 后退一步
this.$router.go(-1);
// 前进一步
this.$router.go(1);
路由传参
可以通过 params 或 query 传递参数。
// 使用 params
this.$router.push({ name: 'user', params: { userId: 123 } });
// 使用 query
this.$router.push({ path: '/user', query: { userId: 123 } });
在目标组件中,可以通过 this.$route.params 或 this.$route.query 获取参数。
// 获取 params
const userId = this.$route.params.userId;
// 获取 query
const userId = this.$route.query.userId;
动态路由匹配
在路由配置中定义动态路径参数。
const routes = [
{ path: '/user/:userId', component: User }
];
在组件中可以通过 this.$route.params.userId 获取动态参数。
导航守卫
可以通过导航守卫控制导航跳转。
router.beforeEach((to, from, next) => {
if (to.path === '/admin' && !isAdmin) {
next('/login');
} else {
next();
}
});
懒加载路由
通过动态导入实现路由懒加载,优化性能。
const User = () => import('./views/User.vue');
const routes = [
{ path: '/user', component: User }
];






