前端路由实现
前端路由实现的方式主要有两个:
1、hash模式
2、history API
使用hash模式来实现一个简单版的前端路由:
function Router () { this.routes = {} } Router.prototype.route = function (url, callback) { this.routes[url] = callback || function () {} } Router.prototype.publish = function (url) { if (this.routes[url]) { this.routes[url].apply(this) } } Router.prototype.init = function () { let currentUrl = window.location.hash.slice(1) || '/' window.addEventListener('load', this.publish.bind(this, currentUrl)) window.addEventListener('hashchange', this.publish.bind(this, currentUrl)) } let Router = new Router() Router.init() Router.route('/one', function () { console.log('hi one!') }) Router.route('/two', function () { console.log('two') }) Router.route('/three', function () { console.log('three') })