hashRouter

hashRouter的基于ES6的基本实现

by ZhiLin GeGe

HTML

<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div class="container">
    <div class="rightSide">
          <div id="myPage">

          </div>
    </div>
    <div class="leftSide">
            <ul>
                <li><a href="#/">默认 </a></li>
                <li><a href="#/blue"> 蓝</a></li>
                <li><a href="#/black">黑 </a></li>
            </ul>
    </div>
</div>
</body>
</html>

CSS

/*css代码比较混乱,大家不用在意这里*/
        * {
            margin: 0;
            padding: 0;
        }
        .container {
            box-sizing: border-box;
        }
        .leftSide {
            display: flex;
            align-items: center;
            justify-content: center; 
            width: 50%;
            height: 300px;

            background-color: #bbb;
        }
        .rightSide {
            display: flex;
            align-items: center;
            justify-content: center; 
            float: right;
            width: 50%;
            height: 300px;
            background-color: #5bb;
        }

JavaScript

(function() {
    class Router {
        constructor() {
            this.routes = {};
            this.currentUrl = "";
        }
        init() {
            window.addEventListener('load', () => this.refresh(), false);
            window.addEventListener('hashchange',() => this.refresh(), false);
        }
        refresh() {
            this.currentUrl = location.hash.slice(1) || "/";
            if (typeof this.routes[this.currentUrl] === 'function') {
                this.routes[this.currentUrl]();
            }else {
                this.routes["/404"]();
            }
            console.log(location.href);//由于这里不知道怎么查看url,所以,只能我通过控制台显示url,大家可以直接把代码拷贝下来本地运行试试;
        }
        route(path, callback) {
            this.routes[path] = callback;
        }
    };

    function changeView(str) {
        document.getElementById("myPage").innerHTML=str;
    }

    var router=new Router();
    router.init();
    router.route("/", () => changeView("<h1>默认页面</h1>"));
    router.route("/blue", () => changeView("<h1>blue页面</h1>"));
    router.route("/black", () => changeView("<h1>black页面</h1>"));
    router.route("/404",() => changeView("<h1>404    请求的页面不存在</h1>"));
})()