JS是如何實現前端路由的

路由就是根據不同的 url 地址展示不同的內容或頁面,早期路由的概念是在後端出現的,通過服務器端渲染後返回頁面,隨着頁面越來越複雜,服務器端壓力越來越大。後來ajax異步刷新的出現使得前端也可以對url進行管理,此時,前端路由就出現了。

單頁面就是有前端路由來實現的,也就是說網站只有一個頁面,點擊導航會顯示不同的內容,對應的url也在發生改變。在這個過程中,js會實時檢測url的變化,從而改變顯示的內容。

路由實現的原理:window綁定了監聽函數,當url的hash值發生變化的時候會觸發hashchange回調,在回調中進行不同的操作,馬上刷新頁面,從而顯示不同的頁面。

下面是一個前端路由的簡單實現:通過路由實現url的切換、頁面內容的改變。

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>前端路由測試</title>
    <script src="../plugins/jQuery/jquery-1.12.4.min.js"></script>

    <style>
        .content {
            width: 50px;
            height: 50px;
            background-color: #00a2d4;
        }
    </style>

</head>
<body>
<ul>
    <li><a href="#/red">turn red</a></li>
    <li><a href="#/blue">turn blue</a></li>
    <li><a href="#/green">turn green</a></li>
</ul>
<div class="content">
</div>

<script src="router.js"></script>
<script src="test.js"></script>

</body>
</html>

router

//構造函數
function Router() {
    this.routes = {};
    this.currentUrl = '';
}
Router.prototype.route = function(path, callback) {
    this.routes[path] = callback || function(){};//給不同的hash設置不同的回調函數
};
Router.prototype.refresh = function() {
    console.log(location.hash.slice(1));//獲取到相應的hash值
    this.currentUrl = location.hash.slice(1) || '/';//如果存在hash值則獲取到,否則設置hash值爲/
    // console.log(this.currentUrl);
    if(this.currentUrl&&this.currentUrl!='/'){
        this.routes[this.currentUrl]();//根據當前的hash值來調用相對應的回調函數
    }

};
Router.prototype.init = function() {
    window.addEventListener('load', this.refresh.bind(this), false);
    window.addEventListener('hashchange', this.refresh.bind(this), false);
}
//給window對象掛載屬性
window.Router = new Router();
window.Router.init();

test.js代碼

Router.route('/red', function () {
    $(".content").css('background-color','red')
});
Router.route('/blue', function () {
    $(".content").css('background-color','blue')
});
Router.route('/green', function () {
    $(".content").css('background-color','green')
});

注意:router.js要在test.js之前進行調用,不然會先加載test.js從而找不到,出現router.js未被定義。

上面router對象實現主要提供了三個方法

1.init監聽瀏覽器url的hash值更新事件。

2.route存儲路由更新時的回調到回調數組routes中,回掉函數將負責對頁面進行更新。

3.refresh執行當前url的回調函數,更新頁面。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章