版权声明:如果您对这个文章有任何异议,那么请在文章评论处写上你的评论。 如果您觉得这个文章有意思,那么请分享并转发,或者也可以关注一下表示您对我们文章的认可与鼓励。 愿大家都能在编程这条路,越走越远。 https://blog.csdn.net/weixin_44369568/article/details/91489491
<!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> 文章来源: https://blog.csdn.net/weixin_44369568/article/details/91489491