前端路由机制

前端路由:在应用使用期间不会重新加载,提高用户体验,减低网速要求,界面展开快。前后端分离方便开发

目前前端路由有两种实现方法:

  1. 利用url的hash,当浏览器url的锚点部分发生改变,不会刷新页面的原理
  2. 利用h5中的history,通过监听opostate事件,利用pushstate或replacestate实现

原生router/hash版

html:

1
2
3
4
5
6
<ul>
<li><a href="#/home">home</a></li>
<li><a href="#/about">about</a></li>
</ul>

<div id="routerView"></div>

js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var routerView=document.querySelector("#routerView");
window.addEventListener("DOMContentLoaded",onchange);
window.addEventListener("hashchange",onchange);

function (){
switch(location.hash){
case "#/home":
routerView.innerHTML="home";
return;
case "#/about":
routerView.innerHTML="about";
return;
default:
routerView.innerHTML="";
return;
}
}

原生router/history版

html:

1
2
3
4
5
6
<ul>
<li>大专栏  前端路由机制tag"><a href="/home">home</a></li>
<li><a href="/about">about</a></li>
</ul>

<div id="routerView"></div>

js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var routerView=document.querySelector("#routerView");

window.addEventListener("popstate",onchange);


document.querySelectorAll("a[href]").forEach(
el=> el.addEventListener("click",function(e){
e.preventDefault(); //阻止A标签默认行为
var path=el.getAttribute("href");
history.pushState(null,"",path); //@param 1)状态对象2)标题3)URL
onchange(); //手动触发
}))
function (){
switch(location.pathname){
case "/home":
routerView.innerHTML="home";
return;
case "/about":
routerView.innerHTML="about";
return;
default:
routerView.innerHTML="";
return;
}
}

总结

hash:

  1. 利用锚点导航(改变URL中的hash不引起页面刷新)
  2. hashchange监听hash变化,(浏览器前后退,a标签,window.location均可触发)

history:

  1. history对象提供了pushState和replaceState方法,这两个方法改变URL不会引起页面刷新
  2. popstate事件,(浏览器前后退可触发,a标签需阻止默认,window.location需改写成history.pushState)
原文地址:https://www.cnblogs.com/lijianming180/p/12147597.html