当前位置:网站首页>Differences between routing modes
Differences between routing modes
2022-04-22 08:13:00 【Lu Rongtao】
Front end routing principle ? What is the difference between the implementation of the two routes ?
1. Generally speaking
hash
history
abstract
Front end routing is mainly used in SPA( Single page development ) In the project . Without refresh , According to URL To display different components or content .
1.hash Pattern
www.test.com/#/ Namely Hash URL, When # When the following hash value changes , Can pass hashchange The incident came to be heard URL The change of , To jump to the page , And no matter how the hash value changes , Received by the server URL The request is always www.test.com.Hash The model is relatively simple , And better compatibility . Every change # The latter part , Will add a record to the browser's access history , Use " back off " Button , You can go back to the previous position .
2.history Pattern
History The pattern is HTML5 New features , The main use of history.pushState and history.replaceState change URL. adopt History Mode change URL It also won't cause page refresh , Only the browser history will be updated . When the user makes a browser action , For example, clicking the back button will trigger popState event .
*popstate event *
When the user clicks on the browser 「 Forward 」、「 back off 」 Button , It will trigger popstate event . You can monitor this event , To respond .
here e.state That's when pushState The first parameter passed in when ,state An object can be anything that can be serialized . Because Firefox will store these objects on the user's disk , So after the user restarts the browser, these state The object is restored .
*replaceState Method *
Sometimes , You don't want to add a new record , Instead, replace the current record ( For example, for the website landing page), You can use replaceState Method . This method and pushState The parameters of are exactly the same .
history.pushState() and history.replaceState() these two items. API There are three parameters , Namely :
*a. State object (state object)* — One JavaScript object , And use pushState() Method . Whenever a user navigates to a newly created state ,popstate Events are triggered , And the object of the event state Property contains a copy of the state object of the history entry .
*b. title (title)* — FireFox This parameter is currently ignored by the browser , Although it may be used in the future . Considering that the method may be modified in the future , It's safer to pass an empty string . perhaps , You can also pass in a short title , Indicate the state to be entered .
*c. Address (URL)* — The address of the new history entry . The browser doesn't call pushState() Method and load the address , But then , You may try to load , For example, the user restarts the browser . new URL Not necessarily the absolute path ; If it's a relative path , It will be based on the current URL Benchmarking ; Incoming URL With the current URL It should be homologous , otherwise ,pushState() It throws an exception . This parameter is optional ; If not specified, it is the current URL.
Two API contrast :
Similarities : Are the two API Will operate the history of the browser , Without causing a page refresh .
The difference is : pushState A new history will be added , and replaceState The current history will be replaced .
2. Extension and extension problems
The difference between the two routing modes
1.Hash The mode can only be changed # Later ,History The mode can be through API Set any homology URL
2.History The mode can be through API Add any type of data to the history ,Hash The mode can only change the hash value , That's string
3.Hash In mode , Refresh multiple times to pass a page , Records are added only once
4.Hash Mode does not require back-end configuration , And good compatibility .History Mode is initiated when the user manually enters the address or refreshes the page URL request , The backend needs to be configured index.html Pages are used when static resources cannot be matched
3 Experience points in the project
When using HTML5 history, When you refresh the page, you will see 404. Because of the present url The server cannot find , therefore , Add a candidate resource to the server that covers all cases : If URL No static resources were matched , The same should be returned index.html page , This page is you app Dependent pages . At the same time, it needs to be handled on the front side 404.
hash Pattern
<body>
<a href="#/"> home page </a>
<a href="#/home"> Home page </a>
<a href="#/list"> list </a>
<div id="box"></div>
</body>
<script>
class Route{
constructor({routes}) {
let box=document.getElementById("box");
this.routes=routes;
this.init()
this.events={};
this.routes.forEach((item,i)=>{
this.events[item.path]=function(){
box.innerHTML=item.component;
}
})
}
init(){
window.addEventListener("hashchange",this.updateVide.bind(this));
}
updateVide(){
//console.log(this.events[path])
let path=window.location.hash.slice(1)
this.events[path]()
}
}
new Route({
routes:[
{
path:"/",
component:" home page "
},
{
path:"/home",
component:" Home page "
},
{
path:"/list",
component:" list "
}
]
})
</script>
history Pattern
<body>
<a href="javascript:;" data-to="/"> home page </a>
<a href="javascript:;" data-to="/home"> Home page </a>
<a href="javascript:;" data-to="/list"> list </a>
<div id="box"></div>
</body>
<script>
class Route{
constructor({routes}) {
this.routes=routes;
this.initHistory();
this.init()
}
initHistory(){
console.log(window,"1111")
window.addEventListener("popstate",()=>{
console.log(window.location,'kkkk')
this.updateView(window.location.pathname)
})
}
init(){
let as=document.querySelectorAll("a");
let _this=this;
[].forEach.call(as,(item)=>{
item.onclick=function(){
let path=item.getAttribute("data-to");
//{} In fact, it is some information transmitted by routing , such as query,search these
//null, I want to modify html label
//path Is the routing address
window.history.pushState({},null,path);
_this.updateView(path);
}
})
}
updateView(path){
let box=document.getElementById("box") box.innerHTML=this.routes.filter(item=>item.path===path)[0].component
}
}
new Route({
routes:[
{
path:"/",
component:" home page "
},
{
path:"/home",
component:" Home page "
},
{
path:"/list",
component:" list "
}
]
})
</script>
* Get Qianfeng education learning video materials + Source notes , Enter the learning exchange group
Please add wechat below ( remarks CSDN recommend )

版权声明
本文为[Lu Rongtao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220637544212.html
边栏推荐
猜你喜欢

2022年全国中职组网络安全国赛赛题思路(仅自己一个做题的思路)——网络安全竞赛试题(7)

Postman intermediate: processing interface encryption and decryption AES SM3 SM4

laravel8-使用jwt

web自动化:8.1如何在浏览器发送js指令

jmeter 参数请求类型

TP5 在 extend 目录下 自定义成功失败返回信息

Postman interface automation-3-tests assertion 3: get dynamic parameters and set environment variables (Interface Association)

Flink 指标参数源码解读(读取数量、发送数量、发送字节数、接收字节数等)
![[technology] how does Siemens soft PLC communicate with configuration software?](/img/a7/c8cb4201f933c24d13118d607f346f.png)
[technology] how does Siemens soft PLC communicate with configuration software?

分布式系统服务熔断
随机推荐
The JMeter interface requests a security authentication solution
PHP 实现 QQ 登录
Selenium driver installation
OpenFeign的参数传递之数组和集合类型
分布式系统服务熔断
MYSQL_从精通到放弃目录
金九银十面试季,字节跳动面试题拿走不谢(附详细答案解析)
The practical paper of Shiping information and data security compliance testing was selected into the Chinese core journals
mysql数据库,索引字符集不一致,slowsql慢查询,接口超时问题
SQL 基础(八)数据更新操作实战演练
2022年全国中职组网络安全国赛赛题思路(仅自己一个做题的思路)——网络安全竞赛试题(7)
Primary test: ordinary vs excellent
web问题定位实战:2.提示信息、字段校验
Navicat误删了连接,如何恢复数据库
ADB logcat log
软件测试面试题汇总
web自动化:8.1如何在浏览器发送js指令
2022年全国中职组网络安全国赛赛题思路(仅自己一个做题的思路)——网络安全竞赛试题(8)
postman接口自动化-3-Tests断言3:获取动态参数,设置环境变量(接口关联)
JS dynamically merge cells