SPA路由原理及實現

單頁面應用中的路由分為兩種: hash模式和history模式

1. hash模式

比如 https://www.google.com/#abc中的hash值為abc
特點:hash的變化不會刷新頁面,也不會發送給服務器。但hash的變化會被瀏覽器記錄下來,用來指導瀏覽器中的前進和后退。
瀏覽器提供了hashchange事件來監聽hash的變化

2. history模式

HTML5中history對象新增的API

  1. 通過pushState()、replaceState()來修改url地址
    區別:pushState會改變history.length,而replaceState不改變history.length
    注意:調用replaceState()或者pushState(),只是修改歷或添加瀏覽器歷史記錄中的條目,并不會刷新或改變頁面。
    手動刷新頁面時,會把請求發送到服務器,如果沒有對應的資源,就會404

  2. popstate事件
    每當活動的歷史記錄項發生變化時,將觸發popstate事件,例如用戶點擊瀏覽器的回退按鈕(或者在Javascript代碼中調用history.back()或者history.forward()方法)。

3. 代碼實現

接下來我們用最簡單的代碼來實現這兩種路由

1) hash router

點此查看效果
實現思路是:監聽hashchange事件,然后更新對應的視圖。
html結構

<div id="app">
    <ul>
        <li><a href="#/">Home</a></li>
        <li><a href="#/topic">Topic</a></li>
        <li><a href="#/about">About</a></li>
    </ul>
    <div id="content"></div>
</div>

js代碼

class HashRouter{
    constructor(){
        this.currentPath = '/';
        this.routes = {}
    }
    init(){
        //DOMContentLoaded事件用于刷新頁面后
        window.addEventListener('DOMContentLoaded', this.updateView.bind(this))
        window.addEventListener('hashchange', this.updateView.bind(this))
    }
    updateView(){
        this.currentPath = location.hash.substring(1) || '/'
        this.routes[this.currentPath] && this.routes[this.currentPath]()
    }
    route(path, callback){
        this.routes[path] = callback
    }
}

const router = new HashRouter();
router.init();
router.route('/', function(){
    document.getElementById('content').innerHTML = 'This is Home'
})
router.route('/topic', function(){
    document.getElementById('content').innerHTML = 'This is Topic'
})
router.route('/about', function(){
    document.getElementById('content').innerHTML = 'This is About'
})

2) history router

history router稍微麻煩一點,我們先思考下,對于一個應用而言,url 的改變(不包括 hash 值得改變)只能由下面三種情況引起:

  • 點擊瀏覽器的前進或后退按鈕 => 可以監聽popstate事件
  • 點擊 a 標簽
  • 在 JS 代碼中觸發 history.pushState()、history.replaceState()

所以history router的實現思路是:監聽頁面中和路由有關的a標簽點擊事件,阻止默認的跳轉行為,然后調用history.pushState()方法,讓瀏覽器記住路由,然后手動更新相應視圖。同時為了監聽用戶手點擊瀏覽器的前進后退按鈕,還需要監聽popstate事件,動態的修改相應視圖。

點此查看效果

html結構

<div id="app">
    <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/topic">Topic</a></li>
        <li><a href="/about">About</a></li>
    </ul>
    <div id="content"></div>
</div>

js代碼

class HistoryRouter{
    constructor(){
        this.currentPath = '/';
        this.routes = {}
    }
    init(){
        //DOMContentLoaded事件用于刷新頁面后
        window.addEventListener('DOMContentLoaded', this.updateView.bind(this, '/'))
        var that = this
        window.addEventListener('click', function (ev) {
            if(ev.target.tagName.toLocaleLowerCase() === 'a' && ev.target.getAttribute('data-href')) {
                ev.preventDefault()
                var path = ev.target.getAttribute('data-href');
                history.pushState({ path: path }, '', path)
                that.updateView(path)
            }
        })
        window.addEventListener('popstate', function (ev) {
            if(ev.state){
                var path = ev.state.path
                that.updateView(path)
            }else{
                that.updateView('/')
            }
        })
    }
    updateView(path){
        this.currentPath = path
        this.routes[this.currentPath] && this.routes[this.currentPath]()
    }
    route(path, callback){
        this.routes[path] = callback
   }
}

var router = new HistoryRouter();
router.init();
router.route('/', function(){
    document.getElementById('content').innerHTML = 'This is Home'
})
router.route('/topic', function(){
    document.getElementById('content').innerHTML = 'This is Topic'
})
router.route('/about', function(){
    document.getElementById('content').innerHTML = 'This is About'
})
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容