當我們在使用react或vue的router作路由跳轉時,為了保持菜單與地址欄狀態一致,我們可以使用window.onhashchange捕獲#后面的變化
window.onhashchange = (hash)=> { var newHash = this.getHashKeyByUrl(hash.newURL); if(newHash == this.getHashKeyByUrl(hash.oldURL)){ return; } // this.setState({curSelectedMenuKey:[newHash]}); console.log("url參數-->",newHash) }; function getHashKeyByUrl(url){ var reg = new RegExp(/#\/(.*)?/); var matches =url.match(reg); if(matches && matches.length>=2 && matches[1]!=undefined){ return matches[1]; }else{ return null; } }