Two working modes of front-end Vue routing

1. The significance of front-end routing

前端路由主要应用在spa项目中。
核心---在无刷新(不向后端发送请求)的情况下,可以根据不同url更改视图。

In the Web front-end single-page application SPA (Single Page Application), routing describes the mapping relationship between URL and UI. This mapping is one-way, that is, URL changes cause UI updates (no need to refresh the page). At present, front-end routing mainly includes two kinds of hash and history. What they have in common is changing the url of the current website page, monitoring changes in the url path, and matching routing rules to display the corresponding content to be displayed (it will not send a request to change the page like the background).

1. hash routing

There is a # number. When the hash value changes, the hashchange function is used to monitor the change of the routing value behind the hash#. Change the page information to be displayed according to different hash values ​​(that is, different routes).

比如这个 URL:http://www.abc.com/#/hello,hashURL模式中#后面的就是hash值,当hash值发生变化时,
可以通过hashChange事件监听到url的变化,从而进行页面跳转。每一次改变#后的部分,都会在浏览器的访问历史中
增加一个记录,使用“后退”按钮,就可以回到上一个位置。

注意:无论hash值如何变化,服务器接收到的HTTP请求中url永远是#前面的http://www.abc.com;对后端完全没有
影响,因此改变 hash 不会重新加载页面。

2. History routing

Listening to path changes in url requires the support of both client and server. Because the request will not be resent to the server when the route changes, but when the page is refreshed, the request will be resent to the server. If the server is not configured, then 404 will be displayed. Through the window.history mode of the
browser record page history

HTML5新推出的功能。主要使用history.pushState() 和history.replaceState() 方法。同时还有一个新的
popState事件(当用户做出浏览器动作,例如点击“前进”、“后退”按钮时,触发popState事件),通过监听这一事件,
配合上面这两个方法应用于浏览器的历史记录栈,在当前已有的 back、forward、go 的基础之上,提供了对当前浏览
器进行修改的功能,实现改变了当前的 URL,但浏览器不会立即向后端发送请求。

注意:history模式更改url不会向后端发送请求,但是如果点击刷新,就会向后端发送请求。

2. The difference between the two modes

1.history模式可以通过api设置任意的同源url,hash模式只可以更改#后的内容;
2.history模式可以通过api添加任意类型的数据到历史记录中,hash模式只能更改hash值,也就是字符串;
3.history模式设置的新 URL 可以与当前 URL 一模一样,这样也会把记录添加到栈中;
  hash 设置的新值必须与原来不一样才会触发动作将记录添加到栈中;
4.hash模式无需后端配置,且兼容性好。
  history模式在用户手动输入url地址或刷新页面时会发起url请求,前端的 URL 必须和实际向后端发起请求的 URL
  致,如 http://www.abc.com/book/id。如果后端缺少对 /book/id 的路由处理,将返回 404 错误。后端需要配置
  index.html页面用于匹配不到静态资源的时候,同时在前端处理4045.history模式可额外设置 title 属性供后续使用。

3. Usage scenarios

In general scenarios, both hash and history are fine, unless you care more about the appearance, the # symbol mixed in the URL does not look very beautiful.
If you don't want an ugly hash, we can use the routing history mode, which makes full use of the history.pushState API to complete URL jumps without reloading the page.

Guess you like

Origin blog.csdn.net/m0_66504310/article/details/129261366