vue路由实现切换
Vue 路由切换的实现方法
Vue Router 是 Vue.js 官方的路由管理器,用于构建单页应用(SPA)。以下是实现路由切换的几种核心方法:
声明式导航
使用 <router-link> 组件实现导航,通过 to 属性指定目标路由:
<router-link to="/home">Home</router-link>
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
编程式导航
通过 this.$router 的 API 实现动态跳转:
// 路径跳转
this.$router.push('/home');
// 命名路由跳转
this.$router.push({ name: 'user', params: { userId: '123' } });
// 替换当前路由(无历史记录)
this.$router.replace('/login');
// 前进/后退
this.$router.go(-1);
动态路由匹配
通过冒号 : 定义动态路径参数:
const routes = [
{ path: '/user/:id', component: User }
];
在组件中通过 this.$route.params.id 获取参数。
嵌套路由
使用 children 属性实现嵌套视图:
const routes = [
{
path: '/user',
component: User,
children: [
{ path: 'profile', component: Profile },
{ path: 'posts', component: Posts }
]
}
];
导航守卫
通过路由钩子控制导航逻辑:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login');
} else {
next();
}
});
路由懒加载
使用动态导入实现代码分割:

const User = () => import('./views/User.vue');
const routes = [
{ path: '/user', component: User }
];
注意事项
- 确保已正确安装和配置 Vue Router:
Vue.use(VueRouter) - 路由组件应避免直接修改
$route对象,使用watch或导航守卫响应变化 - 命名路由需在路由配置中明确定义
name属性 - 动态路由参数变化时,组件实例会被复用,可通过
watch监听$route或使用beforeRouteUpdate钩子






