一. 路由的前世今生
前端开发的同学们,在日常工作中或多或少的会使用到页面的路由。尤其是今年来前端路由框架层出不群,React, Vue 等主流前端框架也都有各自标配。更多的是在单页面应用中,通过路由实现局部刷新,按需加载等都可以通过其关联来实现。那么路由的基本原理怎样?一个路由库是如何实现?解析来我们简要的分析并实践它。
二. 路由的基本原理
1. 常见路由分类
HASH 路由
hash 路由通常在url中会携带 # 字符, 其后部分对应为hash值。hash值的改变会触发onhashchange事件, 但不会引起页面的刷新(重加载)。通常可以在切换hash时通过location.hash.slice(1) ,便可获取对应新hash值。
class HashRouter {
constructor() {
this.routes = {};
this.currentUrl = ""
}
route(path, callback) {
this.routes[`${path}`] = callback || function () { }
}
updateView() {
// 点击的跳转链接的href 内容
this.currentUrl = location.hash.slice(1) || '/';
this.routes[`${this.currentUrl}`] && this.routes[this.currentUrl]();
}
init() {
window.addEventListener('load', this.updateView.bind(this), false);
// 只要hash发生改变即触发hashchange, 包括浏览器自带前进,后退
window.addEventListener('hashchange', ()=>{
console.log("hashchange。。。");
this.updateView()
}, false)
}
}
class HRouter extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
const router = new HashRouter();
router.init();
const regiestRouter = (path, index) => {
router.route(path, () => {
document.getElementById('content').innerHTML = `Page Name ${index}`
})
};
['/', '/about', '/news'].map((path, index) => {
regiestRouter(path, index)
});
}
render() {
return (
<div id="app">
<ul>
<li>
<a href="#/">home</a>
</li>
<li>
<a href="#/about">about</a>
</li>
<li>
<a href="#/news">news</a>
</li>
</ul>
<div id="content"></div>
</div>
)
}
}
export default HRouter ;
如下图点击链接,hash发生变化,页面非刷新,视图会对应发生变化。
HISTORY 路由
History 路由基于HTML5规范,真实的url路由中其没有 “#” ,从而显得更简洁,直观。 在html5规范中提供了 history.pushState, history.replaceState API 及 onpopstate事件来控制路由。 而onpopstate事件,仅在浏览器回退/前进按钮改变时会触发。history 方式路由的改变不会触发任何事件,所以需要想其它的方式来收集路由信息实现。
一个基本的思路是拦截/监听所有可能改变路由的情况: 浏览器前进/后退,点击a标签, js代码中触发history.push(replace)State函数等。
class Router {
constructor() {
this.routes = {};
this.currenetUrl = '';
}
route(path, callback) {
this.routes[path] = callback || function () { }
}
updateView(url) {
this.currenetUrl = url;
this.routes[url] && this.routes[url]();
}
bindLink() {
const allLink = document.querySelectorAll('a[data-href]');
for (let i = 0, len = allLink.length; i < len; i++) {
const current = allLink[i];
current.addEventListener('click',
e => {
e.preventDefault();
const url = current.getAttribute('data-href');
history.pushState({}, null, url);
this.updateView(url);
}
)
}
}
init() {
this.bindLink();
window.addEventListener('popstate', e => {
this.updateView(location.pathname)
});
window.addEventListener('load', () => this.updateView('/historyRouter'), false)
}
}
class HistoryRouter extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
const router = new Router();
router.init();
const regiestRouter = (path, index) => {
router.route(path, () => {
document.getElementById('content').innerHTML = `Page Name ${index}`
})
};
['/historyRouter', '/about', '/news'].map((path, index) => {
regiestRouter(path, index)
});
}
render() {
return (
<div id="app">
<ul>
<li><a data-href="/historyRouter" href="#">home</a></li>
<li><a data-href="/about" href="#">about</a></li>
<li><a data-href="/news" href="#">news</a></li>
</ul>
<div id="content"></div>
</div>
)
}
}
export default HistoryRouter;
效果如下图: 点击导航链接页面路由会发生变化,同时发生局部渲染。从外观上看,不难发现history路由更直观。
React-Router 的实现原理
未完待续…