【vue-rouer源码】系列文章
- 【vue-router源码】一、router.install解析
- 【vue-router源码】二、createWebHistory、createWebHashHistory、createMemoryHistory源码解析
- 【vue-router源码】三、理解Vue-router中的Matcher
- 【vue-router源码】四、createRouter源码解析
- 【vue-router源码】五、router.addRoute、router.removeRoute、router.hasRoute、router.getRoutes源码分析
- 【vue-router源码】六、router.resolve源码解析
- 【vue-router源码】七、router.push、router.replace源码解析
- 【vue-router源码】八、router.go、router.back、router.forward源码解析
- 【vue-router源码】九、全局导航守卫的实现
- 【vue-router源码】十、isReady源码解析
- 【vue-router源码】十一、onBeforeRouteLeave、onBeforeRouteUpdate源码分析
- 【vue-router源码】十二、useRoute、useRouter、useLink源码分析
- 【vue-router源码】十三、RouterLink源码分析
- 【vue-router源码】十四、RouterView源码分析
前言
【vue-router源码】系列文章将带你从0开始了解vue-router
的具体实现。该系列文章源码参考vue-router v4.0.15
。
源码地址:https://github.com/vuejs/router
阅读该文章的前提是你最好了解vue-router
的基本使用,如果你没有使用过的话,可通过vue-router官网学习下。
本篇文章将介绍router.go
、router.back
、router.forward
的实现。
使用
go
函数允许你在历史中前进或后退,指定步数如果>0
,代表前进;<0
代表后退。
router.go(-2)
router.back()
// 等同于
router.go(-1)
router.forward()
// 等同于
router.go(1)
go
go
接收一个参数delta
,表示相对当前页面,移动多少步,负数表示后退,正数表示前进。
const go = (delta: number) => routerHistory.go(delta)
在routerHistory.go
中会调用history.go
,进而触发popstate
监听函数。如果你看过之前createWebHistory
的解析,你会知道在createWebHistory
中通过useHistoryListeners
创建historyListeners
时,会注册一个popstate
监听函数,这个监听函数在调用history.go
后就会触发。
// 文件位置:src/history/html5.ts useHistoryListeners方法
window.addEventListener('popstate', popStateHandler)
const popStateHandler: PopStateListener = ({
state,
}: {
state: StateEntry | null
}) => {
// 当前location,字符串
const to = createCurrentLocation(base,</