<!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>
<div id="app"></div>
<a href="#/mine">我的页面</a>
<a href="#/">主页</a>
<script>
<!-- hash 模式由前端单独完成, 不需要后端配合 -->
class VueRouter {
constructor(router = []) {
this.router = router
this.curHash = ''
this.reFresh = this.reFresh.bind(this)
// url加载完成时调用, hash值变化不会引起页面刷新, 自然不会触发该事件
window.addEventListener('load', this.reFresh, false)
// 浏览器暴露给我们的方法: hashchange, 通过监听 hashchange 事件, 我们可以拿到 url 的 hash 值
window.addEventListener('hashchange', this.reFresh, false)
}
getHash(url) {
return url.indexOf('#') >= 0
? url.slice(url.indexOf('#') + 1)
: '/'
}
reFresh(e) {
console.log(e, 'e')
let newUrl, oldUrl
const { newURL, oldURL } = e
if (newURL) {
newUrl = this.getHash(newURL)
oldUrl = this.getHash(oldURL) || ''
} else {
newUrl = this.getHash(window.location.hash) || ''
}
// 获得当前的 hash 值
this.curHash = newUrl
this.matchComponent()
}
// 匹配当前 hash 对应的路由组件
matchComponent() {
let curRoute = this.router.find((route) => {
return route.path == this.curHash
})
if(!curRoute){
// 取不到对应的路由组件则取第一个,此处简单处理,实际场景按实际情况处理
curRoute = this.router[0]
}
document.querySelector('#app').innerHTML = curRoute.component
console.log(curRoute,'curRoute')
}
}
const Router = new VueRouter([
{
path: '/',
name: 'home',
component: '<div>主页</div>'
},
{
path: '/mine',
name: 'home',
component: '<div>我的</div>'
}
])
</script>
</body>
</html>
02-20
3298
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交