前端路由的两种模式
2021-05-25 本文已影响0人
雷雨leiyu
我们都知道单页应用的路由有两种模式:hash 和 history,那么它们的工作原理是是什么?
浏览器提供的路由跳转API:location与history
location与history都是浏览器的对象:window.location与window.history。
window.location对象
通过改变其属性值修改页面的 url。我们在单页应用中需要做到的是改变 url 不刷新页面。
- location.href:可以改变hash值而不刷新页面;
- location.hash:可以改变hash值而不刷新页面;
- location.search:会刷新页面,改变的是?后面部分;
- location.pathname:会刷新页面,改变的域名部分;
window.history对象
history 接口是 HTML5 新增的,它有两个方法可以改变 url 而不刷新页面。
- history.pushState(state,title,url)
- history.replaceState():方法的参数同上,区别说它修改浏览器历史中当前历史记录。
url变化监听
当路由发生变化的时候我们需要得知这个变化并且调用相应的功能模块,那么这个变化是如何被监听到的呢?事实上是通过浏览器的两个事件来做到的。
- hashchange事件能监听 url hash 的改变;
- popstate事件能监听除 history.pushState() 和 history.replaceState() 外 url 的变化;
// hash模式
window.addEventListener("hashchange", function(e) {
console.log(e);
});
// history模式
window.addEventListener("popchange", function(e) {
console.log(e);
});
hash 模式和 history 模式的选择
history模式:前端的url必须和实际向后端发起请求的url 一致。
hash模式对SEO不友好。
- 在 hash 模式时不使用 history.pushState() 和 history.replaceState() 方法,就只需要在 hashchange 事件回调里编写 url 改变时的逻辑就行了;
- 而 history 模式下,我们不仅要在 popstate 事件回调里处理 url 的变化,还需要分别在 history.pushState() 和 history.replaceState() 方法里处理 url 的变化。而且 history 模式还需要后端的配合,不然用户刷新页面就只有 404 可以看了;
Vue中路由模式的配置
export default new Router({
mode: 'hash', // 或者history
routes: [
{
path: '/',
name: 'home',
component: Home
}
])