前端路由的简单实现

单页应用中,页面的跳转如果只是通过js控制时,浏览器的前进/后退会离开当前url。另外通过url收藏当前页面后重新打开时会跳到应用的初始状态。

用前端路由的方法可以解决上述问题。url的hash部分改变,不会反生页面跳转,但会触发hashchange事件,再通过js显示不同的组件。
简单实现如下:

<ul>
    <li><a href="#/detail">detail</a></li>
    <li><a href="#/error">error</a></li>
</ul>
function Router() {
    this.routes = {};//存储hash和方法的映射
    this.currentUrl = '';
}
//注册路径和方法的映射
Router.prototype.route = function(path, callback) {
    this.routes[path] = callback;
};
//hash改变时触发的事件
Router.prototype.refresh = function() {
    this.currentUrl = location.hash.slice(1) || '/';
    this.routes[this.currentUrl]();
};
Router.prototype.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(); Router.route('/', function() { console.log("主页"); }); Router.route('/detail', function() { console.log("跳转到详情页"); }); Router.route('/error', function() { console.log("出错了"); });
原文地址:https://www.cnblogs.com/kevin2chen/p/6582376.html