react-router实现原理

  1. 获取html文件#后面的部分:
    window.location.hash
  2. 添加onhashchange事件,监听路由变化:
    window.onhashchange = function(){
    }
  3. 完整代码:
    <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>
  4. 效果:
    react-router实现原理
    react-router实现原理
    react-router实现原理
    react-router实现原理

猜你喜欢

转载自blog.51cto.com/12173069/2106022