js 路徑改變時獲取url參數


當我們在使用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;
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM