在以前的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值變了,馬上刷新頁面。
