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來獲取參數,瀏覽器提供了多種事件來支持,對原生事件的一個封裝javascript
function pushHash (path) { if (supportsPushState) { pushState(getUrl(path)) } else { window.location.hash = path } }