文章目录
单页面富应用(SPA)
单页面富应用:single-page application,简称SPA;
单页面富应用是指整个Web应用有一个页面,当 url 发生改变时,并不会从服务器请求新的静态资源,而是通过JavaScript监听 url 的改变,并且根据 url 的不同去渲染新的页面(组件)
前端路由
通过监听URL的改变,并且根据 url 的不同去渲染新的页面(组件),复杂这个工作的就是前端路由。
监听 url 的改变有两种方法吗,一种是 url的 hash,另一种是 html5 的 history
url 的 hash
url 的 hash 也就锚点(#),它本质上改变的是 href 属性。另外可以通过直接赋值location.hash 来改变 href
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
a {
display: inline-block;
padding: 10px 20px;
color: #000000;
text-decoration: none;
border: 1px solid #eeeeee;
}
</style>
</head>
<body>
<a href="#/home">home</a><a href="#/about">about</a>
<div id="router-view"></div>
<script>
const routerView = document.getElementById('router-view');
window.addEventListener('hashchange', () => {
switch(location.hash) {
case "#/home":
routerView.innerHTML = 'home';
break;
case "#/about":
routerView.innerHTML = 'about';
break;
default:
routerView.innerHTML = '404';
}
})
</script>
</body>
html5 的 history
history接口是HTML5新增的, 它有l六种模式改变URL而不刷新页面:
- replaceState:替换原来的路径;
- pushState:使用新的路径;
- popState:路径的回退;
- go:向前或向后改变路径;
- forword:向前改变路径;
- back:向后改变路径;
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
a {
display: inline-block;
padding: 10px 20px;
color: #000000;
text-decoration: none;
border: 1px solid #eeeeee;
}
</style>
</head>
<body>
<a href="/home">home</a>
<a href="/about">about</a>
<div id="router-view"></div>
<script>
const routerView = document.getElementById('router-view');
const aList = document.getElementsByTagName('a');
for (let item of aList) {
item.addEventListener("click", (e) => {
e.preventDefault();
const href = item.getAttribute("href");
console.log