在 Vue.js 中,路由是实现单页应用(SPA)的核心功能之一。Vue 提供了 vue-router
库来管理路由。以下是 Vue 路由的几种常见方式:
)
是 Vue Router 提供的组件,用于声明式导航。它会被渲染成一个 标签,点击后会跳转到指定的路由。
Home
About
this.$router.push
或 this.$router.replace
)通过 JavaScript 代码实现路由跳转。
this.$router.push
:跳转到新路由,并保留历史记录(可以回退)。this.$router.replace
:跳转到新路由,但不会保留历史记录(无法回退)。methods: {
goToHome() {
this.$router.push('/home'); // 跳转到 /home
},
goToAbout() {
this.$router.replace('/about'); // 替换当前路由为 /about
}
}
示例:
动态路由允许根据参数动态匹配路由。路由参数通过 :
定义。
路由配置:
const routes = [
{ path: '/user/:id', component: User }
];
组件中获取参数:
User ID: {{ $route.params.id }}
跳转到动态路由:
this.$router.push('/user/123'); // 跳转到 /user/123
嵌套路由允许在路由中定义子路由,适用于复杂的页面布局。
路由配置:
const routes = [
{
path: '/user',
component: User,
children: [
{ path: 'profile', component: UserProfile }, // /user/profile
{ path: 'posts', component: UserPosts } // /user/posts
]
}
];
父组件(User.vue):
User Page
通过名称来跳转路由,而不是直接使用路径。
路由配置:
const routes = [
{ path: '/home', component: Home, name: 'home' },
{ path: '/about', component: About, name: 'about' }
];
跳转:
this.$router.push({ name: 'home' }); // 跳转到 /home
将某个路径重定向到另一个路径。
路由配置:
const routes = [
{ path: '/', redirect: '/home' }, // 访问 / 时重定向到 /home
{ path: '/home', component: Home }
];
为路由设置别名,访问别名时也会渲染对应的组件。
路由配置:
const routes = [
{ path: '/home', component: Home, alias: '/welcome' } // 访问 /welcome 也会渲染 Home 组件
];
路由守卫用于在路由跳转前或跳转后执行一些逻辑,例如权限验证、登录检查等。
router.beforeEach
router.afterEach
beforeEnter
beforeRouteEnter
、beforeRouteUpdate
、beforeRouteLeave
示例:全局前置守卫
router.beforeEach((to, from, next) => {
if (to.path === '/admin' && !isAuthenticated) {
next('/login'); // 未登录时跳转到登录页
} else {
next(); // 继续导航
}
});
通过动态导入组件,实现路由的懒加载,优化应用性能。
路由配置:
const routes = [
{ path: '/home', component: () => import('./views/Home.vue') },
{ path: '/about', component: () => import('./views/About.vue') }
];
除了动态路由参数,还可以通过 query
或 params
传递参数。
通过 query
传参:
this.$router.push({ path: '/user', query: { id: 123 } }); // 跳转到 /user?id=123
通过 params
传参:
this.$router.push({ name: 'user', params: { id: 123 } }); // 跳转到 /user/123
获取参数:
this.$route.query.id; // 获取 query 参数
this.$route.params.id; // 获取 params 参数
Vue Router 提供了多种路由方式,可以根据需求选择合适的方式:
this.$router.push
或 this.$router.replace
:
定义参数query
或 params
传递参数掌握这些方式可以更好地实现 Vue 应用的路由管理。