vue cli实现跳转
Vue CLI 实现页面跳转的方法
在 Vue CLI 项目中,页面跳转通常通过 Vue Router 实现。以下是几种常见的跳转方式:
使用 <router-link> 组件
<router-link to="/about">跳转到关于页面</router-link>
<router-link> 是 Vue Router 提供的组件,会自动渲染为 <a> 标签,to 属性指定目标路由路径。
编程式导航
在组件方法中使用 this.$router.push:
methods: {
goToAbout() {
this.$router.push('/about');
}
}
也可以传递路由名称(需在路由配置中定义 name):
this.$router.push({ name: 'about' });
带参数的跳转
// 传递参数
this.$router.push({ path: '/user', query: { id: '123' } });
// 或
this.$router.push({ name: 'user', params: { id: '123' } });
在目标组件中通过 this.$route.params.id 或 this.$route.query.id 获取参数。
替换当前路由
使用 replace 方法不会在 history 中留下记录:
this.$router.replace('/about');
路由配置示例
确保在 src/router/index.js 中配置了路由:
const routes = [
{
path: '/about',
name: 'about',
component: () => import('../views/About.vue')
}
];
动态路由匹配
{
path: '/user/:id',
component: User
}
跳转时传递参数:
this.$router.push('/user/123');
在 User 组件中通过 this.$route.params.id 获取参数值。
导航守卫
可以在路由跳转前后执行逻辑:
router.beforeEach((to, from, next) => {
// 跳转前逻辑
next();
});
这些方法覆盖了 Vue CLI 项目中实现页面跳转的主要场景,根据具体需求选择合适的方式。







