美文网首页
React-router 简单实现

React-router 简单实现

作者: ITtian | 来源:发表于2017-08-25 18:22 被阅读8次
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>router</title>
</head>
<body>
    <ul>
        <li><a href="#/">turn white</a></li>
        <li><a href="#/blue">turn blue</a></li>
        <li><a href="#/green">turn green</a></li>
    </ul>
<script>
    // 路由类
    function Router(){
        this.routes = {}
        this.currentUrl = ''
    }

    Router.prototype = {
      constructor: Router,
      router: function(data){
          for(var item of data){
              this.routes[item.path] = item.getComponent || function (){}
          }

      },
      refresh: function(){
          console.log(this)
          this.currentUrl = location.hash.slice(1) || '/'
          this.routes[this.currentUrl]()
      },
      init: function (){
          window.addEventListener('load',this.refresh.bind(this),false)
          window.addEventListener('hashchange',this.refresh.bind(this),false)
      }
    }

    window.Router = new Router()
    // 注册路由改变事件
    window.Router.init()

    var content = document.querySelector('body')

    function changeBgColor(color){
        content.style.backgroundColor = color
    }


    var routes_data = [
      {
        path: '/',
        getComponent: function(){
            changeBgColor('white')
        }
      },
      {
        path: '/blue',
        getComponent: function(){
            changeBgColor('blue')
        }
      },
      {
        path: '/green',
        getComponent: function(){
            changeBgColor('green')
        }
      },
    ]
    
    // 注册路由表
    Router.router(routes_data)
</script>
</body>
</html>

原文地址https://github.com/joeyguo/blog/blob/master/lab/2016/router/simple-router.html

相关文章

网友评论

      本文标题:React-router 简单实现

      本文链接:https://www.haomeiwen.com/subject/rbhpdxtx.html