Vue Router 基础回顾
Vue Router 是 Vue.js 官方路由管理器。它和 Vue.js 深度集成,让构建单页应用变得简单。
动态路由匹配
路由参数
1 2 3 4 5 6 7 8
| { path: '/user/:id', component: User }
this.$route.params.id
|
响应路由参数变化
1 2 3 4 5
| watch: { '$route' (to, from) { } }
|
嵌套路由
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| { path: '/user/:id', component: User, children: [ { path: 'profile', component: UserProfile }, { path: 'posts', component: UserPosts } ] }
|
编程式导航
1 2 3 4 5 6 7 8
| this.$router.push('/home')
this.$router.replace('/home')
this.$router.go(-1)
|
路由守卫
全局守卫
1 2 3 4 5 6 7
| router.beforeEach((to, from, next) => { if (to.name !== 'Login' && !isAuthenticated) { next({ name: 'Login' }) } else { next() } })
|
路由独享守卫
1 2 3 4 5 6 7
| { path: '/admin', component: Admin, beforeEnter: (to, from, next) => { } }
|
组件内守卫
1 2 3 4 5 6 7 8 9 10 11
| export default { beforeRouteEnter (to, from, next) { }, beforeRouteUpdate (to, from, next) { }, beforeRouteLeave (to, from, next) { } }
|
路由懒加载
1
| const User = () => import('./User.vue')
|
滚动行为
1 2 3 4 5 6 7
| scrollBehavior (to, from, savedPosition) { if (savedPosition) { return savedPosition } else { return { x: 0, y: 0 } } }
|
总结
Vue Router 功能强大,掌握这些高级用法能让你构建更复杂的应用。多实践,多参考官方文档。