在以前的web程序中,路由字眼只出现在后台中。但是随着SPA单页面程序的发展,便出现了前端路由一说。单页面顾名思义就是一个网站只有一个html页面,但是点击不同的导航显示不同的内容,对应的url也会发生变化,这就是前端路由做的事。也就是通过JS实时检测url的变化,从而改变显示的内容。
目前很多前端框架都有接口去实现路由,比如vuejs的vue-route等。我们可以利用原生的hashchange事件来模拟一个简单的路由。
实例的html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.content{
position:absolute;
left: 0px;
top:0px;
display: none;
}
.content:nth-child(1){
display: block;
}
</style>
<script src="js/jquery-2.2.1.min.js"></script>
</head>
<body>
<div id="index-page" class="content">
<ul>
<li><a href="#/index">index</a></li>
<li><a href="#/news">news</a></li>
<li><a href="#/about">about</a></li>
</ul>
</div>
<div id="news-page" class="content">
<h1>this is new page</h1>
<a href="#/index">back</a>
</div>
<div id="about-page" class="content">
<h1>this is about page</h1>
<a href="#/index">back</a>
</div>
<script src="js/bundle.js"></script>
</body>
</html>
实例的javascript代码:
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) || '/index';
this.routes[this.currentURL]();
}
Router.prototype.init = function () {
window.addEventListener('load',this.refresh.bind(this),false);
window.addEventListener('hashchange',this.refresh.bind(this),false);
}
function display_page(id){
$(".content").eq(id).show().siblings().hide();
}
window.Router = new Router();
Router.route('/index',function(){
display_page(0);
})
Router.route('/news',function(){
display_page(1);
})
Router.route('/about',function(){
display_page(2);
})
window.Router.init();
- Router是一个路由类,类属性routes是一个路由映射对象,currentURL表示当前的URL
- 类函数route表示为对应的url指定视图函数,refresh函数为刷新页面函数
- 为window绑定监听函数,其中主要绑定hashchang,以检测到hash值变了,马上刷新页面。