Vue Router
Vue Router 是 Vue.js 的官方路由。它与 Vue.js 核心深度集成,让用 Vue.js 构建单页应用变得轻而易举。
核心概念
<router-link>
<router-link>可以实现页面跳转,帮助我们生成正确的URL
<router-view>
<router-view>可以根据当前路由渲染匹配的组件
嵌套路由
在路由配置中,给当前路由添加一个children属性,这样就实现了在一个路由内部嵌套了另一个路由。
// 访问 xxxxxx/parent/child
const routes = [
{
path: '/parent',
component: ParentComponent,
children: [
{
path: 'child',
component: ChildComponent
}
]
}
]
hash模式和history模式
它们的主要区别在于URL中的 # 符合
hash模式
http://example.com/#/foo/bar
history模式
http://example.com/foo/bar
- hash 模式:默认情况下,Vue Router 使用 hash 模式来管理路由。在 hash 模式下,URL 中的路由信息会被存放在
#符号后面 - 由于 hash 不会被包括在 HTTP 请求中,因此不会影响服务器的处理,同时也不会导致页面的刷新,因此 hash 模式在单页应用程序中被广泛使用。
- history 模式:history 模式需要在服务器上进行配置才能正常使用。
- 由于 history 模式使用的是浏览器的 history API,因此可以使用前进和后退按钮来实现页面的导航,而且 URL 更加直观,不需要带有
#符号。
导航守卫
导航守卫用于在路由切换过程中拦截并处理路由请求,常用的例如: beforeEach, afterEach等
懒加载
如果应用有大量组件或页面,那么首次加载需要加载大量的JavaScript代码,导致页面加载缓慢,我们将路由的component配置项设置为一个返回Promise的函数,实现按需加载
const router = [
{ path: '/foo', component: () => import('./Foo.vue') }
]
懒加载在实现按需加载的同时也增加了一定的代码复杂度。
导航守卫 实现路由权限控制
设置白名单,当路由进入这些页面时,不拦截
const whiteList: Record<string, 'exact' | 'startsWith'> = {
'/': 'exact',
'/items': 'exact',
'/welcome': 'startsWith',
'/sign_in': 'startsWith',
}
router.beforeEach((to, from) => {
for (const key in whiteList) {
const value = whiteList[key]
if (value === 'exact' && to.path === key) {
return true
}
if (value === 'startsWith' && to.path.startsWith(key)) {
return true
}
}
// 登录校验通过则允许进入,失败则跳转到登录页面
return mePromise!.value!.then(
() => true,
() => '/sign_in?return_to=' + from.path
)
})