(转发)前端路由history模式与hash模式

history模式(推荐)
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>前端路由实现</title>
  <style>
    .warp{
      width:400px;
      height:400px;
      border:1px solid grey;
      margin:0 auto;
    }
    .nav{
      border-bottom:1px solid grey;
    }
    .nav li{
      display:inline-block;
      list-style:none;
    }
    .nav li a{
      display:inline-block;
      text-decoration: none;
      padding:10px 15px;
    }
    .router{
      padding:20px;
    }
    a{
      cursor: pointer;
    }
  </style>

</head>
<body>
<section class="warp">
  <div class="nav">
    <ul>
      <li><a href="javascript:void(0)" data-path="index">首页</a></li>
      <li><a href="javascript:void(0)" data-path="news">新闻</a></li>
      <li><a href="javascript:void(0)" data-path="about">关于</a></li>
    </ul>
  </div>
  <div id="router" class="router">
    <!-- 内容加载区域 -->
  </div>
</section>

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
  ;(function(){
    history.replaceState(null,null,'');//最开始的状态,采用replace直接替换
    $('#router').html('<p>nav1</p>')
    $('a').on('click',function(){
      console.log(this.text)
      var text = this.text;
      $('#router').html('<p>'+ text +'</p>')
      history.pushState(null,null,'#/'+text);
    })
  })()
</script>

</body>
</html>

hash模式
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  function Router() {
    this.routes = {};
    this.currentUrl = '';
  }
  Router.prototype.route = function(path, callback) {
    this.routes[path] = callback || function(){};//给不同的hash设置不同的回调函数
  };
  Router.prototype.refresh = function() {
    console.log(location.hash.slice(1));//获取到相应的hash值
    this.currentUrl = location.hash.slice(1) || '/';//如果存在hash值则获取到,否则设置hash值为/
    // console.log(this.currentUrl);
    this.routes[this.currentUrl]();//根据当前的hash值来调用相对应的回调函数
  };
  Router.prototype.init = function() {
    window.addEventListener('load', this.refresh.bind(this), false);
    window.addEventListener('hashchange', this.refresh.bind(this), false);
  }
  //给window对象挂载属性
  window.Router = new Router();
  window.Router.init();

  Router.route('/', function() {
    console.log("test");
  });
  Router.route('/1', function() {
    console.log("aaa");
  });
  Router.route('/2', function() {
    console.log("bbb");
  });
</script>
</body>
</html>

history模式中popstate(event),pushstate(state,title,url),replacestate(state,title,url),三者调用参考:
https://www.jb51.net/html5/606481.html

猜你喜欢

转载自blog.csdn.net/qq_33332184/article/details/90161368