原生JS实现一个简单的前端路由(原理)

说一下前端路由实现的简要原理,以 hash 形式(也可以使用 History API 来处理)为例,

当 url 的 hash 发生变化时,触发 hashchange 注册的回调,回调中去进行不同的操作,进行不同的内容的展示。

直接看代码或许更直观。

 1 function Router() {
 2     this.routes = {};
 3     this.currentUrl = '';
 4 }
 5 Router.prototype.route = function(path, callback) {
 6     this.routes[path] = callback || function(){};
 7 };
 8 Router.prototype.refresh = function() {
 9     this.currentUrl = location.hash.slice(1) || '/';
10     this.routes[this.currentUrl]();
11 };
12 Router.prototype.init = function() {
13     window.addEventListener('load', this.refresh.bind(this), false);
14     window.addEventListener('hashchange', this.refresh.bind(this), false);
15 }
16 window.Router = new Router();
17 window.Router.init();

上面路由系统 Router 对象实现,主要提供三个方法

  • init 监听浏览器 url hash 更新事件
  • route 存储路由更新时的回调到回调数组routes中,回调函数将负责对页面的更新
  • refresh 执行当前url对应的回调函数,更新页面

Router 调用方式以及呈现效果如下:点击触发 url 的 hash 改变,并对应地更新内容(这里为 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> 
var content = document.querySelector('body');
// change Page anything
function changeBgColor(color) {
    content.style.backgroundColor = color;
}
Router.route('/', function() {
    changeBgColor('white');
});
Router.route('/blue', function() {
    changeBgColor('blue');
});
Router.route('/green', function() {
    changeBgColor('green');
});

 

 

posted @ 2017-05-11 10:04  安慕希  阅读(7806)  评论(0编辑  收藏  举报