Router 是用于创建单页应用,即不用刷新就可以实现页面切换,有以下两种模式
hash 模式跳转链接带 # 号,不用全路径匹pi配,匹配#号后面的路径
history 模式需要全路径匹配,刷新会 404,需要配置 ng
hash路由原理
使用 Javascript 来对 location.hash 进行赋值,改变 URL 的hash值
使用 hashchange 事件来监听 hash 值的变化
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="handleClick('#/home')">/home</button>
<button onclick="handleClick('#/user')">/user</button>
<div id="content"></div>
<script>
//监听 hashchange
window.addEventListener("hashchange", (e) => {
console.log(e);
let hash = e.newURL.split('#')[1]
const content = document.getElementById('content')
switch(hash){
case '/home': content.innerHTML='主页';
break;
case '/user': content.innerHTML='用户';
break;
default: break
}
})
function handleClick(type){
location.hash = type
}
</script>
</body>
</html>
history路由原理
HTML5 提供了 History API 来实现 URL 的变化,其中最主要的 API 有以下两个:
history.pushState() 新增一个历史记录
history.replaceState() 直接替换当前的历史记录
这两个 API 可以在不进行刷新的情况下,操作浏览器的历史纪录
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="handleClick('/home')">/home</button>
<button onclick="handleClick('/user')">/user</button>
<div id="content"></div>
<script>
//重写 pushState 方法
let oldPushState = history.pushState
// history.replaceState
history.pushState = function (data, title, url) {
oldPushState.call(this, data, title, url)
const content = document.getElementById('content')
switch(url){
case '/home': content.innerHTML='主页'
break;
case '/user': content.innerHTML='用户'
break;
default: break
}
}
function handleClick(type){
// history.replaceState
history.pushState({},'',type)
}
</script>
</body>
</html>