前端路由监听
# 前言
前端路由监听是通过两个事件来做到的,分别是 哈希改变 和 history改变
# 哈希改变
hashchange
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<a href="#/home">首页</a>
<a href="#/about">关于</a>
<div class="router-view"></div>
</div>
<script>
// 获取router-view的DOM
const routerView = document.querySelector(".router-view");
// 监听URL的改变
window.addEventListener("hashchange", () => {
switch (location.hash) {
case "#/home":
routerView.innerHTML = "首页";
break;
case "#/about":
routerView.innerHTML = "关于";
break;
default:
routerView.innerHTML = "404";
}
})
</script>
</body>
</html>
# history改变
popstate
pushState、replaceState
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<a href="/home">首页</a>
<a href="/about">关于</a>
<div class="router-view"></div>
</div>
<script>
// 1.获取router-view的DOM
const routerView = document.querySelector(".router-view");
// 获取所有的a元素, 自己来监听a元素的改变
const aList = document.querySelectorAll("a");
for (let el of aList) {
el.addEventListener("click", event => {
event.preventDefault();
const href = el.getAttribute("href");
// data, title, url
history.pushState({}, "", href);
urlChange();
})
}
// 执行返回操作时, 依旧来到urlChange
window.addEventListener('popstate',urlChange);
// 监听URL的改变
function urlChange() {
switch (location.pathname) {
case "/home":
routerView.innerHTML = "首页";
break;
case "/about":
routerView.innerHTML = "关于";
break;
default:
routerView.innerHTML = "404";
}
}
</script>
</body>
</html>
# 总结
实现前端路由的监听是一件很容易的事情,毕竟官方提供了api。
通过监听hash和判断location的hash 或者 监听所有跳转标签的单击、以及history的state变更还有判断location的pathname,这些都可以实现前端路由的监听的效果。
上次更新时间: 10年18月2023日 01时57分53秒