0%

Vue Router 高级用法

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 功能强大,掌握这些高级用法能让你构建更复杂的应用。多实践,多参考官方文档。