react-router实现原理
- 获取html文件#后面的部分:
window.location.hash
- 添加onhashchange事件,监听路由变化:
window.onhashchange = function(){ }
- 完整代码:
<a href="#/home">home</a> <a href="#/index">index</a> <a href="#/other">other</a> <div id="box"></div> <script> window.onhashchange = function(){ var hash = window.location.hash.slice(1) var box = document.getElementById('box') if(hash=='/home'){ box.innerHTML = "home" }else if(hash=='/index'){ box.innerHTML = "index" }else{ box.innerHTML = "default" } } </script>
- 效果: