4. createWebHistory()
1. 整体情况
1.1 方法源码
// 文件 history/html5.ts
export function createWebHistory(base?: string): RouterHistory {
// 规范化 base,兼容 <base> 标签,删除值尾部的 /
base = normalizeBase(base)
// 返回一个包含 location, state 属性和 push, replace 方法的对象
const historyNavigation = useHistoryStateNavigation(base)
// 返回一个包含 pauseListeners, listen, destroy 方法的对象
const historyListeners = useHistoryListeners(
base,
historyNavigation.state,
historyNavigation.location,
historyNavigation.replace
)
function go(delta: number, triggerListeners = true) {
if (!triggerListeners) historyListeners.pauseListeners()
history.go(delta) // 原生方法 window.history.go()
}
// 赋值
const routerHistory: RouterHistory = assign(
{
location: '',
base,
go,
createHref: createHref.bind(null, base), // 移除 hash 前的所有字符
},
historyNavigation,
historyListeners
)
// 两个 getter
Object.defineProperty(routerHistory, 'location', {
enumerable: true,
get: () => historyNavigation.location.value,
})
Object.defineProperty(routerHistory, 'state', {
enumerable: true,
get: () => historyNavigation.state.value,
})
return routerHistory
}1.2 属性来源
RouterHistory 接口定义的属性和方法
来源
1.3 逻辑分析
2. 监听 popstate 事件
popstate 事件2.1 useHistoryListeners()
useHistoryListeners()2.2 私有方法 popStateHandler
popStateHandler2.3 调用方法 listen()
listen()3. 维护 Router History 栈
3.1 useHistoryStateNavigation()
useHistoryStateNavigation()4. 路由跳转
公共逻辑
处理 base 和 href
useHistoryStateNavigation(base)
useHistoryStateNavigation(base)附录
state 相关
Last updated
