版权声明:转载需注明出处 https://blog.csdn.net/samfung09/article/details/80851199
前端路由主要有两种实现方式
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.currentUrl]();
}
//窗口监视
Router.prototype.init = function(){
//窗口监视hash变化事件,从而自动触发该路由规则
window.addEventListener('load', this.refresh.bind(this), false);
window.addEventListener('hashchange', this.refresh.bind(this), false);
}
index.html
<a href="#/">首页</a>
<a href="#/news">新闻页</a>
<script>
var router = new Router();
router.route('/', function(){
var div = document.querySelector('#content');
div.innerHTML = '<h2>这是首页</h2>';
})
router.route('/news', function(){
var div = document.querySelector('#content');
div.innerHTML = '<h2>这是新闻页</h2>';
})
</script>