美文网首页
前端路由实现原理 demo

前端路由实现原理 demo

作者: Allan要做活神仙 | 来源:发表于2018-08-26 13:36 被阅读18次

Hash

function Router() {
  this.routes = {};
  this.currentUrl = "";
}
Router.prototype.route = function(path, callback) {
  this.routes[path] = callback || function() {};
};
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();

var content = document.querySelector("body");
// change Page anything
function changeBgColor(color) {
  content.style.backgroundColor = color;
}

Router.route("/", function() {
  changeBgColor("white");
});
Router.route("/orange", function() {
  changeBgColor("orange");
});
Router.route("/purple", function() {
  changeBgColor("purple");
});

相关文章

  • 前端路由实现原理 demo

    Hash

  • 前端路由的简易实现

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

  • 面试:谈谈对前端路由的理解?

    面试官想听到什么答案呢? 1、为什么会出现前端路由。 2、前端路由解决了什么问题。 3、前端路由实现的原理是什么。...

  • SPA 中前端路由原理与实现方式

    SPA 中前端路由原理与实现方式 通常 SPA 中前端路由有2中实现方式,本文会简单快速总结这两种方法及其实现: ...

  • vue路由

    今日目标 1.能够说出什么是路由2.能够说出前端路由的实现原理3.能够使用Vue-Router实现前端路由4.能够...

  • vue路由

    今日目标 1.能够说出什么是路由2.能够说出前端路由的实现原理3.能够使用Vue-Router实现前端路由4.能够...

  • vue面试题(第九天)

    1.Vue路由的实现原理 更新视图但不重新请求页面,是前端路由原理的核心之一 vue路由的实现有两种模式<1>ha...

  • 前端路由实现

    前端路由 前端路由实现原理,就是根据不同的 url ,在页面上显示相应的内容。 hash 浏览器 url 变化时,...

  • 前端路由

    什么是前端路由 前端路由的前生今世及实现原理 先有的SPA,页面内部交互无刷新,再到页面跳转也无刷新,因此路由出现了

  • React Router-简单原理

    以下内容主要参考自 深入理解 react-router 路由系统react-router的实现原理前端路由实现与 ...

网友评论

      本文标题:前端路由实现原理 demo

      本文链接:https://www.haomeiwen.com/subject/xcloiftx.html