前端路由主要有两种实现方式
1、location.hash+hashchange事件。
2、history.pushState()+popstate事件。
第一种、location.hash+hashchange事件
这种方式的优势就是浏览器兼容性较好。
当页面url地址发生改变时,location.hash获取hash值,比如"www.xxx.com/#/home",location.hash的值为"#/home",如果是"www.xxx.com",location.hash则为空。hashchange事件监听hash值,然后根据这个值来匹配设置好的路由规则。看代码
router.js
function Router(){
//路由目录
this.routes = {};
//当前url地址
this.currentUrl = '';
this.init();
}
//添加路由规则
Router.prototype.route = function(path, cb){
//存储path对应的回调函数
this.routes[path] = cb || function(){};
}
//路由刷新
Router.prototype.refresh = function(){
//获取当前url的hash值
this.currentUrl = location.hash.slice(1) || '/';
console.log(this, this.currentUrl)
//执行当前路由回调函数
this.routes[this.currentUrl] && this.routes[this.currentU