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