前端路由笔记

11次阅读

共计 1078 个字符,预计需要花费 3 分钟才能阅读完成。

前端路由的实现本质:检测 URL 变化,获取 url 地址,解析 url 匹配页面;检测 URL 变化有两种方式:hash,HTML5 History

HTML5 History history.pushState 和 history.replaceState 这两个 api 都分别接收三个参数:状态对象,标题,url(此 url 地址不支持跨域,跨域会报错) 这两个 API 都会操作浏览器的历史记录,并不引起浏览器的刷新,pushState 会增加一条新的历史记录,replaceState 会替换当前的历史记录;popstate 事件,需要注意的是调用 history.pushState() 或 history.replaceState() 不会触发 popstate 事件。只有在做出浏览器动作时,才会触发该事件,如用户点击浏览器的回退按钮,或者在 Javascript 代码中调用 3.back()。原理在点击某个路由时执行 pushState,在操作浏览器时执行 popstate;
hash location.hash window.location 修改 hash 至不会引起页面刷新,而是当作新页面加到历史记录中。hash 值变化会触发 hashchange 事件。

Function Router(){
this.currentUrl = ”;
this.routes = {};
}

Router.prototype.route = function(url, callback){
this.routes[url] = 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);
}
// 使用
var $target = $(‘#target’);
var route = new Router();
route.init();
route.route(‘/’, $target.html(‘this is index page!!’) );
route.route(‘/page1’, $target.html(‘this is page1!!’));

正文完
 0