Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前端路由理解 #12

Open
HolyZheng opened this issue Jun 25, 2018 · 0 comments
Open

前端路由理解 #12

HolyZheng opened this issue Jun 25, 2018 · 0 comments

Comments

@HolyZheng
Copy link
Owner

HolyZheng commented Jun 25, 2018

作者:holyZheng
转载请注明出处

多页应用和单页应用

多页应用

  • 多页应用中每个html页面作为一个功能组件,通过刷新,请求等方式,组合这些htm页面。前端充当一个展示层,项目的重心偏向后端,往往由后端来主导项目。
  • 当页面有所变化时,页面就会刷新,会造成资源的浪费和用户体验的下降

单页应用

  • 路由处理和数据层前置到前端,后端只需提供相关数据api,良好的前后端分离,减轻后端压力。
  • 后端的一套api可用于网页和移动端app等
  • 内容改变无须再刷新整个页面,提高用户体验。

单页应用的缺点

  • 首次加载大量资源,因为要在一个页面上提高所有功能。
  • 不利于SEO,因为数据在前端渲染。

前端路由

传统路由时在后端出现的,简单说路由就是用来和后端服务器进行交互的一种方式,通过不同路路径,请求不同的资源。

提一下ajax,ajax让我们可以在不刷新页面的情况下进行交互,提升了用户体验,而前端路由使得我们可以无刷新的实现页面跳转。

前端路由实现方式

History API

重点在于 history.pushStatehistory.replaceState这两个api,pushState会增加一条新的历史记录,replaceState会替换当前的历史记录,他们都接收三个参数(不支持跨域)

  • state,存储当前路由对应状态
  • title,标题
  • url,地址

这两个api操作浏览器的历史记录,但是不会引起页面的刷新,可以通过

window.history.pushState({page: 1, ....}, null, "https://xxxx");
window.history.pushState({....}, null, "?name=orange");

添加历史记录,并根据新的url手动更新页面组件。当我们在历史记录中切换的时候,会触发popState事件,我们可以在返回的事件对象中e.state中获取到历史记录对应的state。

 window.addEventListener('popstate', e => {...})

整体流程图
h5_history
图转载自hwencc同学

ps: window.history 还有 back()回退,forward()前进,go()前进或退后等api

hash

原理是url中hash部分的值改变的时候,浏览器不刷新页面,但是会触发hashchange事件,所以我们可以在hashchange事件中,根据新的hash值,手动更新页面组件

window.addEventListener('hashchange', () => {})

ps:window.location属性有 href 整个url,protocol协议,host域名,port端口,hash哈希,origin来源域名

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant