1.react-router-dom的原理(hash和history)
<!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>
<a href="#/home">首页</a>
<a href="#/profile">个人</a>
<a href="/home">首页history</a>
<a href="/profile">个人history</a>
<h1 id="router-view"></h1>
<script>
const route = document.getElementById("router-view");
let clickDom = null;
// 创建路由
function createRouter(types) {
if (types === "hash") {
window.addEventListener("hashchange", () => urlChange(types));
} else {
window.addEventListener("popstate", () => urlChange(types));
}
linkClick(types);
}
// 根据路由地址变化,进行操作
function urlChange(types) {
if (types === "hash") {
switch (location.hash) {
case "#/home":
route.innerHTML = "home:" + clickDom.innerHTML;
break;
case "#/profile":
route.innerHTML = "profile:" + clickDom.innerHTML;
break;
default:
break;
}
} else {
switch (location.pathname) {
case "/home":
route.innerHTML = "home:" + clickDom.innerHTML;
break;
case "/profile":
route.innerHTML = "profile:" + clickDom.innerHTML;
break;
default:
break;
}
}
}
// a点击事件的绑定
function linkClick(types) {
const doms = document.getElementsByTagName("a");
for (let d of doms) {
d.addEventListener("click", (e) => {
if (types === "hash") {
clickDom = d;
return;
}
e.preventDefault();
clickDom = d;
const href = clickDom.getAttribute("href");
history.pushState({ name: clickDom.innerHTML }, "标题", href);
urlChange(types);
});
}
}
// createRouter("hash");
createRouter("history");
</script>
</body>
</html>