前端路由的实现

2019-04-04  本文已影响0人  笑笑料料

浏览器中window.location属性window.history属性

export function FrontRouter() {
  this.routes = {};
  this.preHash = '/';
  this.curHash = '/';
  window.addEventListener('load', this.resolve.bind(this), false);
  window.addEventListener('hashchange', this.resolve.bind(this), false);
}

FrontRouter.prototype.route = function(path, callback) {
  this.routes[path] = callback || function() {};
};

FrontRouter.prototype.back = function() {
  location.hash = '#' + this.preHash;
  console.log('pre_hash:', location.hash);
}

FrontRouter.prototype.resolve = function() {
  this.preHash = this.curHash;
  this.curHash = location.hash.slice(1) || '/';
  typeof this.routes[this.curHash] === 'function' &&
    this.routes[this.curHash]();
};
上一篇 下一篇

猜你喜欢

热点阅读