利用JS實現前端路由

來源:互聯網
上載者:User

標籤:後台   javascrip   list   als   vuejs   網站   對象   false   abs   

在以前的web程式中,路由字眼只出現在後台中。但是隨著SPA單頁面程式的發展,便出現了前端路由一說。單頁面顧名思義就是一個網站只有一個html頁面,但是點擊不同的導航顯示不同的內容,對應的url也會發生變化,這就是前端路由做的事。也就是通過JS即時檢測url的變化,從而改變顯示的內容。

目前很多前端架構都有介面去實現路由,比如vuejs的vue-route等。我們可以利用原生的hashchange事件來類比一個簡單的路由。

 

執行個體的html代碼:

Document

  • index
  • news
  • about
this is new pagebackthis is about pageback

 

執行個體的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();
  1. Router是一個路由類,類屬性routes是一個路由映射對象,currentURL表示當前的URL
  2. 類函數route表示為對應的url指定視圖函數,refresh函數為重新整理頁面函數
  3. 為window綁定監聽函數,其中主要綁定hashchang,以檢測到hash值變了,馬上重新整理頁面。

利用JS實現前端路由

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.