前端于我
hash / history / router

Hash路由以及History路由的实现原理以及优缺点

Hash路由的实现原理

通过变更location.hash来进行路由的改变,通过window.onHashChange来监听hash的变化,再根据hash判断需要显示什么页面

History路由的实现原理

通过HTML5提供的History API来实现URL的变化。

其中主要的两个API:

history.pushState();
history.replaceState();

这两个API可以在不刷新页面的情况下,操作浏览器的历史记录。

例:

window.history.pushState(null, null, path);
window.history.replaceState(null, null, path);

其他常用API:

window.history.back(); // 后退
window.history.forward(); // 前进
window.history.go(2); // 跳转到指定页面,当前为0
window.history.length // 历史堆栈中页面的数量

监听history的路由变化:

window.addEventListener(‘pop state’, function() {
  var currentState = history.state;
});

// 或者
window.onpopstate = function() {}

Hash路由的优缺点

优点:

缺点:

History路由的优缺点

优点:

缺点:

history之pushState,replaceState详解

pushState接收三个参数(状态对象,标题,url)

window.history.pushState({title: '首页1'}, '首页2', '/index');
window.addEventlister('popstate', function(e) { // 或者window.onpopstate
    const state = e.state;
    document.title = state.title; // 首页1
  });

注意 pushState 绝对不会触发hashchange事件,即使仅仅新的url的hash与旧的url的hash不一样

replaceState

replaceState的传参与pushState一样,唯一不同的是replaceState不会产生新的历史记录,而是直接替换掉当前记录

未完待续

参考文档

https://developer.mozilla.org/zh-CN/docs/Web/API/History_API
https://router.vuejs.org/zh/guide/essentials/
<history-mode.html#%E5%90%8E%E7%AB%AF%E9%85%8D%E7%BD%AE%E4%BE%8B%E5%AD%90>

发表于: 2019-10-08