1-关于vue-router的源码分析
1-vue-router 实例化时会初始化 this.history,不同mode对应不同的history
constructor (options: RouterOptions = {}) { this.mode = mode switch (mode) { case 'history': this.history = new HTML5History(this, options.base) break // 我们常用的就是hash,进入这个,调用这个HashHistory方法 case 'hash': this.history = new HashHistory(this, options.base, this.fallback) break case 'abstract': this.history = new AbstractHistory(this, options.base) break default: if (process.env.NODE_ENV !== 'production') { assert(false, `invalid mode: ${mode}`) } } }
2-这里以HashHistory为例,vue-router1的push方法实现如下:
push (location: RawLocation, onComplete?: Function, onAbort?: Function) {
// $flow-disable-line
if (!onComplete && !onAbort && typeof Promise !== 'undefined') {
return new Promise((resolve, reject) => {
this.history.push(location, resolve, reject)
})
} else {
进入这里,调用
this.history.push(location, onComplete, onAbort)
}
}
3-其实底层都是通过window.location一系列API来获取参数,浏览器提供了多种事件来支持,对原生事件的一个封装
function pushHash (path) {
if (supportsPushState) {
pushState(getUrl(path))
} else {
window.location.hash = path
}
}

浙公网安备 33010602011771号