history路由
<!DOCTYPE html>
<html lang="zh-CN">
<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>history路由</title>
</head>
<body>
<div class="router">
<a href="./">首页</a>
<a href="./user">用户列表</a>
<a href="./about">关于我们</a>
</div>
<div class="content"></div>
<script>
class BaseRouter {
constructor () {
this.routes = {}
}
route (path, cb) {
this.routes[path] = cb || function () {}
}
go (path) {
window.history.pushState({path}, null, path)
const cb = this.routes[path]
if (cb) cb()
}
}
const Route = new BaseRouter()
Route.route('./', () => {changeText('这是首页页面')})
Route.route('./user', () => {changeText('这是用户页面')})
Route.route('./about', () => {changeText('这是关于我们页面')})
function changeText (text) {
let dom = document.querySelector('.content')
dom.innerHTML = text
}
document.querySelector('.router').addEventListener('click', e => {
if (e.target.tagName === 'A') {
e.preventDefault()
Route.go(e.target.getAttribute('href'))
}
})
</script>
</body>
</html>
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>hash 路由</title>
</head>
<body>
<div id="container">
<a href="#">首页</a>
<a href="#about">关于我们</a>
<a href="#user">用户列表</a>
</div>
<div id="context"></div>
<script>
class BaseRouter {
constructor() {
this.routes = {};
this.refresh = this.refresh.bind(this);
window.addEventListener('load', this.refresh);
window.addEventListener('hashchange', this.refresh);
};
route(path, cb) {
this.routes[path] = cb || function(){};
};
refresh() {
const path = `/${window.location.hash.slice(1) || ''}`;
this.routes[path]();
}
}
const Route = new BaseRouter();
Route.route('/about', () => changeText("关于我们页面"));
Route.route('/user', () => changeText("用户列表页"));
Route.route("/", () => changeText("首页页面"));
function changeText(arg) {
document.getElementById('context').innerHTML = arg;
}
</script>
</body>
</html>