[|滴滴金融客服电话|]

原生路由的实现

在HTML5的 history API 出现之前,前端的路由都是通过 hash 来实现的,hash 能兼容低版本的浏览器。当 url 的 hash 发生变化时,触发 hashchange 注册的回调,回调中去进行不同的操作,进行不同的内容的展示。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>路由</title>
  </head>
  <body>
     <ul>
        <li><a href="#/">默认路由</a></li>
        <li><a href="#/router1">路由1</a></li>
        <li><a href="#/router2">路由2</a></li>
    </ul>
    <div id="content"></div>
  </body>
  <script type="text/javascript">
    class Router{
       constructor(routes = {}) {
            this.routes = routes;
            this.curUrl = "";
        } 
        route(path,callback){
          this.routes[path] = callback || function(){
          }
        }
        refresh(){
          this.curUrl = location.hash.slice(1) || '/';
          if(this.routes[this.curUrl]){
            this.routes[this.curUrl]();
          }else{
            console.log('路由没有注册');
          }
        }
        init(){
           window.addEventListener('load', this.refresh.bind(this), false);
           window.addEventListener('hashchange', this.refresh.bind(this), false);
        }
    }
    
    function changeContent(text){
      document.getElementById('content').innerHTML = text;
    }
    let router = new Router({
      '/' : function(){
        changeContent('默认路由');
      },
      '/router1':function(){
        changeContent('路由1');
      }
    })

    router.route('/router2',function(){
      changeContent('路由2');
    })

    router.init();
  </script>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值