第14篇:Vue Router 高级用法与路由守卫
目标:掌握路由模式、导航守卫、懒加载等进阶功能
1. 路由模式:Hash vs History
Vue Router 支持两种模式:
-
Hash 模式:通过 URL 的哈希部分(如
http://example.com/#/home
)实现路由,兼容性好,无需服务器配置11。 -
History 模式:基于 HTML5 History API(如
http://example.com/home
),URL 更简洁,但需服务器支持重定向11。
配置方式:
const router = createRouter({
history: createWebHashHistory(), // Hash 模式
// history: createWebHistory(), // History 模式
routes
})
2. 路由元信息(Meta Fields)
通过 meta
字段为路由添加自定义信息(如页面权限、标题):
{
path: '/admin',
component: AdminPage,
meta: {
requiresAuth: true,
title: '管理后台'
}
}
使用场景:
-
在导航守卫中校验权限
-
动态修改页面标题
3. 路由懒加载
优化首屏加载速度,按需加载组件:
const routes = [
{
path: '/profile',
component: () => import('./views/Profile.vue') // 动态导入
}
]
原理:利用 Webpack 的代码分割功能,将组件拆分为独立 chunk。
4. 导航守卫进阶
全局前置守卫:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isLoggedIn()) {
next('/login') // 跳转登录页
} else {
next() // 放行
}
})
路由独享守卫:
{
path: '/dashboard',
component: Dashboard,
beforeEnter: (to, from) => {
// 仅对该路由生效
}
}
组件内守卫:
<script setup>
import { onBeforeRouteLeave } from 'vue-router'
onBeforeRouteLeave(() => {
return confirm('未保存的更改将丢失,确定离开?')
})
</script>
5. 动态路由与参数传递
动态路径参数:
{
path: '/user/:userId',
component: User
}
获取参数:
<script setup>
import { useRoute } from 'vue-router'
const route = useRoute()
console.log(route.params.userId)
</script>
查询参数:
router.push({ path: '/search', query: { keyword: 'vue' } })
// 获取:route.query.keyword
6. 路由嵌套与命名视图
嵌套路由:
{
path: '/settings',
component: SettingsLayout,
children: [
{ path: 'profile', component: Profile },
{ path: 'security', component: Security }
]
}
命名视图(多组件布局):
<router-view name="sidebar"></router-view>
<router-view></router-view>
{
path: '/',
components: {
default: Home,
sidebar: Sidebar
}
}
实战建议:
-
权限控制:结合
meta
字段和全局守卫实现路由权限1114。 -
错误处理:配置 404 页面捕获未匹配路由14:
{ path: '/:pathMatch(.*)*', component: NotFound }
-
性能优化:对非核心路由使用懒加载,减少首屏体积11。