前端路由实现demo(Hash+Histroy)

<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
</style>
<script>
  // hash 使用时请将history相关注释,因为DOMContentLoaded方法和hashchange冲突
  function Router(){
    this.curUrl='';
    this.routes=[];
    this.refresh=function(){
      this.curUrl='/' + location.hash.slice(1);
      console.log(location.hash,this.curUrl);
      this.routes[this.curUrl]();
    };
    this.init=function(){
      window.addEventListener('hashchange',this.refresh.bind(this));
      window.addEventListener('load',this.refresh.bind(this));
    };
    this.route=function(path,callback){
      console.log(callback);
      this.routes[path] = callback || function(){};
    }
  }
  var r= new Router();
  r.route('/',function(){
    var domdiv = document.querySelector("#text");
    domdiv.innerText = '1';
  });
  r.route('/2',function(){
    var domdiv = document.querySelector("#text");
    domdiv.innerText = '2';
  });
  r.route('/3',function(){
    var domdiv = document.querySelector("#text");
    domdiv.innerText = '3';
  });
  r.init();


  // history 使用时请将hash相关注释,因为DOMContentLoaded方法和hashchange冲突
  window.addEventListener('DOMContentLoaded', onLoad)
  window.addEventListener('popstate', onPopState)
  var routerView = null
  function onLoad () {
    routerView = document.querySelector('#routeView')
    onPopState()
    // 拦截 <a> 标签点击事件默认行为, 点击时使用 pushState 修改 URL并更新手动 UI,从而实现点击链接更新 URL 和 UI 的效果。
    var linkList = document.querySelectorAll('a[href]')
    linkList.forEach(el => el.addEventListener('click', function (e) {
      e.preventDefault()
      history.pushState(null, '', el.getAttribute('href'))
      onPopState()
    }))
  }
  // 路由变化时,根据路由渲染对应 UI
  function onPopState () {
    switch (location.pathname) {
      case '/home':
        routerView.innerHTML = 'Home'
        return
      case '/about':
        routerView.innerHTML = 'About'
        return
      default:
        return
    }
  }
</script>
</head>
<body>
  <!-- // hash -->
  <a href="#">1</a>&nbsp;&nbsp;&nbsp;&nbsp;
  <a href="#2">2</a>&nbsp;&nbsp;&nbsp;&nbsp;
  <a href="#3">3</a>
  <h1 id="text">1</h1>

  <!-- // history -->
  <ul>
      <li><a name="home" href='/home'>home</a></li>
      <li><a name="about" href='/about'>about</a></li>
      <div id="routeView"></div>
  </ul>
</body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容