單頁(yè)面應(yīng)用中的路由分為兩種: hash模式和history模式
1. hash模式
比如 https://www.google.com/#abc中的hash值為abc
特點(diǎn):hash的變化不會(huì)刷新頁(yè)面,也不會(huì)發(fā)送給服務(wù)器。但hash的變化會(huì)被瀏覽器記錄下來(lái)腐魂,用來(lái)指導(dǎo)瀏覽器中的前進(jìn)和后退沸久。
瀏覽器提供了hashchange事件來(lái)監(jiān)聽hash的變化
2. history模式
HTML5中history對(duì)象新增的API
通過(guò)pushState()盒揉、replaceState()來(lái)修改url地址
區(qū)別:pushState會(huì)改變history.length昼蛀,而replaceState不改變history.length
注意:調(diào)用replaceState()或者pushState(),只是修改歷或添加瀏覽器歷史記錄中的條目辱士,并不會(huì)刷新或改變頁(yè)面纵潦。
手動(dòng)刷新頁(yè)面時(shí)徐鹤,會(huì)把請(qǐng)求發(fā)送到服務(wù)器,如果沒有對(duì)應(yīng)的資源邀层,就會(huì)404popstate事件
每當(dāng)活動(dòng)的歷史記錄項(xiàng)發(fā)生變化時(shí)返敬,將觸發(fā)popstate事件,例如用戶點(diǎn)擊瀏覽器的回退按鈕(或者在Javascript代碼中調(diào)用history.back()或者h(yuǎn)istory.forward()方法)寥院。
3. 代碼實(shí)現(xiàn)
接下來(lái)我們用最簡(jiǎn)單的代碼來(lái)實(shí)現(xiàn)這兩種路由
1) hash router
點(diǎn)此查看效果
實(shí)現(xiàn)思路是:監(jiān)聽hashchange事件劲赠,然后更新對(duì)應(yīng)的視圖。
html結(jié)構(gòu)
<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事件用于刷新頁(yè)面后
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稍微麻煩一點(diǎn)秸谢,我們先思考下凛澎,對(duì)于一個(gè)應(yīng)用而言,url 的改變(不包括 hash 值得改變)只能由下面三種情況引起:
- 點(diǎn)擊瀏覽器的前進(jìn)或后退按鈕 => 可以監(jiān)聽popstate事件
- 點(diǎn)擊 a 標(biāo)簽
- 在 JS 代碼中觸發(fā) history.pushState()估蹄、history.replaceState()
所以history router的實(shí)現(xiàn)思路是:監(jiān)聽頁(yè)面中和路由有關(guān)的a標(biāo)簽點(diǎn)擊事件预厌,阻止默認(rèn)的跳轉(zhuǎn)行為,然后調(diào)用history.pushState()方法元媚,讓瀏覽器記住路由,然后手動(dòng)更新相應(yīng)視圖苗沧。同時(shí)為了監(jiān)聽用戶手點(diǎn)擊瀏覽器的前進(jìn)后退按鈕刊棕,還需要監(jiān)聽popstate事件,動(dòng)態(tài)的修改相應(yīng)視圖待逞。
html結(jié)構(gòu)
<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事件用于刷新頁(yè)面后
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'
})