原生js 模拟Vue路由切换
实现原理:进啊听hashchange,hash改变的时候,根据当前的hash匹配相应的html内容,然后用innerHTMl把html内容放进router-view里面
<!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 class="container">
<ul>
<li><a href="#/">主页</a></li>
<li><a href="#b">B</a></li>
<li><a href="#c">C</a></li>
</ul>
<div class="viewer">
这是主页的内容
</div>
</div>
</body>
</html>
<style>
body,
html {
width: 100%;
padding: 0;
margin: 0;
height: 100%;
}
.container {
justify-content: center;
align-items: center;
font-size: 60px;
display: flex;
height: 100%;
width: 100%;
}
.viewer {
width: 50%;
height: 20%;
border: 2px solid red;
margin-left: 30px;
}
</style>
<script>
class Router {
constructor() {
this.routes = new Map()
this.currentUrl = ''
this.refresh = this.refresh.bind(this)
window.addEventListener('load', this.refresh, false)
window.addEventListener('hashchange', this.refresh, false)
}
route(path, callback) {
this.routes.set(path, callback)
}
refresh() {
this.currentUrl = location.hash.slice(1) || '/'
console.log(this.currentUrl)
this.routes.get(this.currentUrl)()
}
}
const routes = new Router()
let viewer = document.querySelector('.viewer')
routes.route('/', function () {
viewer.innerHTML = '这是主页面'
})
routes.route('b', function () {
console.log(1)
viewer.innerHTML = '这是B页面'
})
routes.route('c', function () {
viewer.innerHTML = '这是C页面'
})
console.log(routes.routes)
</script>