1. 程式人生 > 程式設計 >JS實現前端路由功能示例【原生路由】

JS實現前端路由功能示例【原生路由】

本文例項講述了JS實現前端路由功能。分享給大家供大家參考,具體如下:

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

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

JS實現前端路由功能示例【原生路由】

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

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

index.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="https://www.jq22.com/jquery/jquery-3.3.1.js"></script>
 
  <style>
      *{
        margin:0;
        padding: 0;
      }

      .content{
        width: 500px;
        height: 300px;
        margin-top: 30px;
        margin:20px auto 0;
      }

      #click_btn{
        width: 500px;
        height: 50px;
        margin:100px auto 0;
      }

      #click_btn a{
        display: block;
        background: #333;
        color: #fff;
        text-decoration: none;
        line-height: 50px;
        text-align: center;
        float: left;
        margin-right: 15px;
        padding: 0px 15px;
      }

      #click_btn a:hover{
        background: #666;
      }
  </style>
 
</head>
<body>
<div id="click_btn">
  <a href="#/one" rel="external nofollow" >第一個頁面</a>
  <a href="#/two" rel="external nofollow" >第二個頁面</a>
  <a href="#/three" rel="external nofollow" >第三個頁面</a>
</div>

<div class="content"></div>
 
<script src="router.js"></script>
<script src="test.js"></script>
 
</body>
</html>

router.js

//建構函式
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',false);
}
//給window物件掛載屬性
window.Router = new Router();
window.Router.init();

test.js

Router.route('/one',function () {
  $(".content").html("<p>路由就是根據不同的 url 地址展示不同的內容或頁面,早期路由的概念是在後端出現的,通過伺服器端渲染後返回頁面,隨著頁面越來越複雜,伺服器端壓力越來越大。後來ajax非同步重新整理的出現使得前端也可以對url進行管理,此時,前端路由就出現了。</p>");
});
Router.route('/two',function () {
  $(".content").html("<h3>單頁面就是有前端路由來實現的,也就是說網站只有一個頁面,點選導航會顯示不同的內容,對應的url也在發生改變。在這個過程中,js會實時檢測url的變化,從而改變顯示的內容。</h3>");
});
Router.route('/three',function () {
  $(".content").html("<img src='https://upload-images.jianshu.io/upload_images/12890819-f8665293cc8d0dcf.png?imageMogr2/auto-orient/strip|imageView2/2/w/1200/format/webp' width='500'/>");
});

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

上面router物件實現主要提供了三個方法

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

2.route儲存路由更新時的回撥到回撥陣列routes中,回掉函式將負責對頁面進行更新。

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

感興趣的朋友可以使用線上HTML/CSS/JavaScript前端程式碼除錯執行工具:http://tools.jb51.net/code/WebCodeRun測試上述程式碼執行效果。

更多關於JavaScript相關內容可檢視本站專題:《JavaScript切換特效與技巧總結》、《JavaScript遍歷演算法與技巧總結》、《JavaScript查詢演算法技巧總結》、《JavaScript動畫特效與技巧彙總》、《JavaScript錯誤與除錯技巧總結》、《JavaScript資料結構與演算法技巧總結》及《JavaScript數學運算用法總結》

希望本文所述對大家JavaScript程式設計有所幫助。