美文网首页
前端路由的简单实现

前端路由的简单实现

作者: 程序猿吴彦祖 | 来源:发表于2018-07-23 16:31 被阅读0次

    es6

        class Routers {
            constructor() {
            this.routes = {};
            this.currentUrl = '';
            this.refresh = this.refresh.bind(this);
    
            window.addEventListener('load', this.refresh, false)
            window.addEventListener('hashchange', this.refresh, false)
        }
    
        route(path, callback) {
            this.routes[path] = callback || function () {}
        }
    
        refresh() {
            console.log(JSON.stringify(location.hash.slice));
            this.currentUrl = location.hash.slice(1) || '/';
            this.routes[this.currentUrl]();
        }
    }
    

    es5

    function Routers() {
        this.routes = {};
        this.currentUrl = '';
        this.refresh = this.refresh.bind(this);
        window.addEventListener('load', this.refresh, false)
        window.addEventListener('hashchange', this.refresh, false)
    }
    Routers.prototype.route = function (path, callback) {
        this.routes[path] = callback || function () {}
    }
    Routers.prototype.refresh = function () {
        this.currentUrl = location.hash.slice(1) || '/';
        console.log(this.name)
        this.routes[this.currentUrl]();
    }

    相关文章

      网友评论

          本文标题:前端路由的简单实现

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