当前版本: 3.0.3
类目录: src/history/base.js
前言:
对于vue-router来说,有三种路由模式history,hash,abstract, abstract是运行在没有window的环境下的,这三种模式都是继承于history类,history实现了一些共用的方法,对于一开始看vue-router源码来说,可以从这里开始看起。
初始属性
router: Router; 表示VueRouter实例。实例化History类时的第一个参数
base: string; 表示基路径。会用normalizeBase进行规范化。实例化History类时的第二个参数。
current: Route; 表示当前路由(route)。
pending: ?Route; 描述阻塞状态。
cb: (r: Route) => void; 监听时的回调函数。
ready: boolean; 描述就绪状态。
readyCbs: Array<Function>; 就绪状态的回调数组。
readyErrorCbs: Array<Function>; 就绪时产生错误的回调数组。
errorCbs: Array<Function>; 错误的回调数组 // implemented by sub-classes
<!-- 下面几个是需要子类实现的方法,这里就先不说了,之后写其他类实现的时候分析 -->
+go: (n: number) => void;
+push: (loc: RawLocation) => void;
+replace: (loc: RawLocation) => void;
+ensureURL: (push?: boolean) => void;
+getCurrentLocation: () => string;
对于history类来说,主要是下下面两个函数的逻辑
transitionTo
这个方法主要是对路由跳转的封装, location接收的是HTML5History,HashHistory,AbstractHistory, onComplete是成功的回调,onAbort是失败的回调
transitionTo (location: RawLocation, onComplete?: Function, onAbort?: Function) {
const route = this.router.match(location, this.current) // 解析成每一个location需要的route
this.confirmTransition(route, () => {
this.updateRoute(route)
onComplete && onComplete(route)
this.ensureURL() // fire ready cbs once
if (!this.ready) {
this.ready = true
this.readyCbs.forEach(cb => { cb(route) })
}
}, err => {
if (onAbort) {
onAbort(err)
}
if (err && !this.ready) {
this.ready = true
this.readyErrorCbs.forEach(cb => { cb(err) })
}
})
}
confirmTransition
这是方法是确认跳转,route是匹配的路由对象, onComplete是匹配成功的回调, 是匹配失败的回调
confirmTransition(route: Route, onComplete: Function, onAbort?: Function) {
const current = this.current
const abort = err => { // 异常处理函数
if (isError(err)) {
if (this.errorCbs.length) {
this.errorCbs.forEach(cb => { cb(err) })










