单页面应用中的路由分为两种: hash模式和history模式
1. hash模式
比如 https://www.google.com/#abc中的hash值为abc
特点:hash的变化不会刷新页面,也不会发送给服务器。但hash的变化会被浏览器记录下来,用来指导浏览器中的前进和后退。
浏览器提供了hashchange事件来监听hash的变化
2. history模式
HTML5中history对象新增的API
通过pushState()、replaceState()来修改url地址
区别:pushState会改变history.length,而replaceState不改变history.length
注意:调用replaceState()或者pushState(),只是修改历或添加浏览器历史记录中的条目,并不会刷新或改变页面。
手动刷新页面时,会把请求发送到服务器,如果没有对应的资源,就会404popstate事件
每当活动的历史记录项发生变化时,将触发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'
})