<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<div class="router_box">
<a href="/home" class="router" replace="true">吃饭</a>
<a href="/news" class="router">睡觉</a>
<a href="/team" class="router">打豆豆</a>
<a href="/about100" class="router">喝酒</a>
</div>
<div id="router-view"></div>
<script>
function Router(params){
this.routes=params.routes||[];
this.mode=params.mode||'hash';
this.init=function(){
document.querySelectorAll(".router").forEach(item=>{
item.addEventListener('click',(e)=>{
if(e && e.preventDefault){
e.preventDefault()
}else{
window.event.returnValue=false
}
if(this.mode=='hash'){
if(item.getAttribute('replace')){
var i=window.location.href.indexOf('#');
window.location.replace(
window.location.href.slice(0,i>=0?i:0)+'#'+item.getAttribute('href')
)
}else{
window.location.hash=item.getAttribute('href')
}
}else{
if(item.getAttribute('replace')){
window.history.replaceState({},'',window.location.origin+item.getAttribute('href'))
}else{
window.history.pushState({},'',window.location.origin+item.getAttribute('href'))
}
}
this.routerChange()
},false)
});
//监听路由变化
if(this.mode=='hash'){
window.addEventListener('hashchange',()=>{
this.routerChange()
})
}else{
window.addEventListener('popstate',e=>{
this.routerChange()
})
}
this.routerChange();
},
//路由改变监听事件
this.routerChange=function(){
if(this.mode=='hash'){
let nowHash=window.location.hash;
let index=this.routes.findIndex(item=>{
return nowHash==('#'+item.path)
})
if(index>=0){
document.querySelector('#router-view').innerHTML=this.routes[index].component;
}else{
let defaultIndex=this.routes.findIndex(item=>item.path=='*')
if(defaultIndex>=0){
const i = window.location.href.indexOf('#')
window.location.replace(
window.location.href.slice(0,i>=0?i:0)+'#'+this.routes[defaultIndex].redirect
)
}
}
}else{
let path=window.location.href.replace(window.location.origin,'');
let index=this.routes.findIndex(item=>path==item.path)
if(index>=0){//找到对应的路由
document.querySelector('#router-view').innerHTML=this.routes[index].component
}else{
let defaultIndex=this.routes.findIndex(item=>item.path=='*')
if(defaultIndex>=0){
window.history.replaceState({},'',window.location.origin+this.routes[defaultIndex].redirect)
this.routerChange();
}
}
}
}
this.init()
}
new Router({
mode:'hash',
routes:[ { path: '/home', component: '<h1>主页</h1><h4>吃饭饭</h4>' },
{ path: '/news', component: '<h1>内容</h1><h4>睡觉觉</h4>' },
{ path: '/team', component: '<h1>列表</h1><h4>打豆豆</h4>' },
{ path: '/about', component: '<h1>关于</h1><h4>高薪工作</h4>' },
{ path:'*', redirect:'/home'}]
})
</script>
</body>
</html>
路由的实现原理---完整的demo
最新推荐文章于 2024-08-05 11:00:00 发布