Skip to content

Instantly share code, notes, and snippets.

@Jiahonzheng
Last active February 21, 2021 14:14
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Jiahonzheng/078c1a935302b03926113cb211a4147f to your computer and use it in GitHub Desktop.
前端路由实现方式
{
"name": "frontend-router",
"version": "1.0.0",
"scripts": {
"vanilla.hash": "serve -c vanilla.hash.json ./",
"vanilla.history": "serve -c vanilla.history.json ./"
},
"dependencies": {
"serve": "^11.3.0"
}
}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Hash Route - Vanilla</title>
</head>
<body>
<ul>
<!-- 定义路由 -->
<li><a href="#/home">home</a></li>
<li><a href="#/about">about</a></li>
<!-- 渲染路由对应的 UI -->
<div id="routeView"></div>
</ul>
<script src="vanilla.hash.js"></script>
</body>
</html>
// 维护 UI 页面。
let routerView = null;
// 路由变化时,根据路由渲染对应 UI 页面。
function onHashChange() {
switch (window.location.hash) {
case '':
case '#/home':
routerView.innerHTML = 'Home';
return;
case '#/about':
routerView.innerHTML = 'About';
break;
default:
}
}
// 页面加载完不会触发 hashchange,这里主动触发一次 hashchange 事件。
window.addEventListener('DOMContentLoaded', () => {
routerView = document.querySelector('#routeView');
onHashChange();
});
// 监听路由变化。
window.addEventListener('hashchange', onHashChange);
{
"rewrites": [
{
"source": "**",
"destination": "vanilla.hash.html"
}
]
}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>History Route - Vanilla</title>
</head>
<body>
<ul>
<!-- 定义路由 -->
<li><a href="/home">home</a></li>
<li><a href="/about">about</a></li>
<!-- 渲染路由对应的 UI -->
<div id="routeView"></div>
</ul>
<script src="vanilla.history.js"></script>
</body>
</html>
// 维护 UI 页面。
let routerView = null;
// 路由变化时,根据路由渲染对应 UI 页面。
function onPopState() {
switch (window.location.pathname) {
case '/':
case '/home':
routerView.innerHTML = 'Home';
return;
case '/about':
routerView.innerHTML = 'About';
break;
default:
}
}
// 页面加载完不会触发 hashchange,这里主动触发一次 hashchange 事件。
window.addEventListener('DOMContentLoaded', () => {
routerView = document.querySelector('#routeView');
// 刷新页面。
onPopState();
// 拦截 <a> 标签点击事件默认行为, 点击时使用 pushState 修改 URL并更新手动 UI,从而实现点击链接更新 URL 和 UI 的效果。
const links = document.querySelectorAll('a[href]');
links.forEach(el =>
el.addEventListener('click', function handler(e) {
e.preventDefault();
// 手动拦截。
window.history.pushState(null, '', el.getAttribute('href'));
onPopState();
}),
);
});
// 监听路由变化。
window.addEventListener('popstate', onPopState);
{
"rewrites": [
{
"source": "**",
"destination": "vanilla.history.html"
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment