用vue实现界面跳转
使用 router-link 组件
Vue Router 提供了 router-link 组件,用于声明式导航。通过 to 属性指定目标路由路径,生成一个可点击的链接。
<router-link to="/home">跳转到首页</router-link>
若需动态传递参数,可通过对象形式:
<router-link :to="{ path: '/user', query: { id: 123 } }">用户页</router-link>
编程式导航
通过 this.$router.push() 方法实现跳转,通常在方法或生命周期钩子中调用。
methods: {
goToHome() {
this.$router.push('/home');
},
goToUser() {
this.$router.push({ path: '/user', params: { id: 1 } });
}
}
使用 replace 方法可替换当前历史记录:
this.$router.replace('/login');
动态路由传参
在路由配置中定义动态参数(如 :id),通过 params 传递:
// 路由配置
const routes = [
{ path: '/user/:id', component: User }
];
跳转时传递参数:
this.$router.push({ path: '/user/123' });
// 或
this.$router.push({ name: 'user', params: { id: 123 } });
命名路由
为路由配置 name 属性,通过名称跳转更清晰:
// 路由配置
const routes = [
{ path: '/home', name: 'home', component: Home }
];
跳转时使用名称:
this.$router.push({ name: 'home' });
路由模式配置
在创建路由实例时指定 history 或 hash 模式:
const router = new VueRouter({
mode: 'history', // 或 'hash'
routes
});
history模式依赖服务器配置,需避免 404 问题。hash模式通过 URL 的#部分实现,无需服务器支持。
监听路由变化
通过 watch 监听 $route 对象,响应路由参数变化:
watch: {
'$route'(to, from) {
console.log('路由变化', to.path);
}
}
导航守卫
使用全局或局部守卫控制跳转逻辑,例如验证登录状态:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isLoggedIn()) {
next('/login');
} else {
next();
}
});
路由懒加载
通过动态导入组件提升性能:
const User = () => import('./views/User.vue');
const routes = [
{ path: '/user', component: User }
];
以上方法覆盖了 Vue 中实现界面跳转的主要场景,根据实际需求选择合适的方式即可。







