前端路由

前端路由的两种实现方式:

1. location.hash + hashchange

function Router(){
    this.curUrl = '';
    this.routes  = {};
}
Router.prototype = {
    route(path, callback){
        this.routes[path] = callback || function(){}
    },
    refresh(){
        this.curUrl = location.hash.slice(1) || '';
        this.routes[this.curUrl]();
    },
    init(){
        window.addEventListener('load', this.refresh.bind(this), false);
        window.addEventListener('hashchange', this.refresh.bind(this), false);
    }
}

// 实例
var r = new Router();
r.init();
function changecolor(color){
  var body = document.getElementsByTagName('body')[0];
  body.style['background'] = color;
}
r.route('/',changecolor.bind(null,'#aaa'));

 

2. history API

    pushState(state, title, url)添加记录,replaceState修改记录,popState(只有在前进后退时触发)

(function(){
    var a = document.getElementById('a');
    var b = document.getElementById('b');
    var c1 = 0;
    var c2 = 0;
    history.replaceState({c1:c1,c2:c2},null,'');
    a.addEventListener('click',function(){
        c1++;        
        history.pushState({c1:c1,c2:c2},null,'#/a'+c1);
        a.innerHTML = 'a'+c1;
    })
    b.addEventListener('click',function(){
        c2++;
        history.pushState({c1:c1,c2:c2},null,'#/b'+c2);
        b.innerHTML = 'b'+c2;
    })
    window.addEventListener('popstate',function(e){
        console.log(e.state);
        a.innerHTML = 'a'+e.state.c1;
        b.innerHTML = 'b'+e.state.c2;
    })
}())

 

posted @ 2018-01-28 17:26  we are young  阅读(265)  评论(0编辑  收藏  举报