標籤:後台 javascrip list als vuejs 網站 對象 false abs
在以前的web程式中,路由字眼只出現在後台中。但是隨著SPA單頁面程式的發展,便出現了前端路由一說。單頁面顧名思義就是一個網站只有一個html頁面,但是點擊不同的導航顯示不同的內容,對應的url也會發生變化,這就是前端路由做的事。也就是通過JS即時檢測url的變化,從而改變顯示的內容。
目前很多前端架構都有介面去實現路由,比如vuejs的vue-route等。我們可以利用原生的hashchange事件來類比一個簡單的路由。
執行個體的html代碼:
Document
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();
- Router是一個路由類,類屬性routes是一個路由映射對象,currentURL表示當前的URL
- 類函數route表示為對應的url指定視圖函數,refresh函數為重新整理頁面函數
- 為window綁定監聽函數,其中主要綁定hashchang,以檢測到hash值變了,馬上重新整理頁面。
利用JS實現前端路由