实现简易版的路由 手动实现vue中的hash路由(上)

实现简易版的路由 手动实现vue中的hash路由

思路就是 创建一个构造函数 然后将routes中的path与location中的hash对应起来。
缺点: 没有重定向以及对于错误的跳转处理机制 待更新

<!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, maximum-scale=1, user-scalable=no">
    <meta name="author" content="陈如斌">
    <title></title>
    <style>
      section:nth-child(n){
          border: 2px solid red;
      }
      section:nth-child(2n) {
          border: 2px solid green;
      }
    </style>
</head>
<body>
  <nav>
      <a class="link" href="/">首页</a>
      <a class="link" href="/b">b页面</a>
      <a class="link" href="/c">c页面</a>
    
  
   
  </nav>
    <section id="home">
        <p>This is home Page</p>
    </section>
    <section id="a">
        <p>This is a page</p>
    </section>
    <section id="c">
        <p>这是c页面</p>
    </section>
    
<script>    
// 将location的hash与路由中的path对应起来  实现路由页面切换
    class Router {
        constructor({mode,routes}){
            this.routes=routes
            // 当hash发生发生改变的时候触发的方法
            // https://developer.mozilla.org/zh-CN/docs/Web/API/Window/hashchange_event
            window.onhashchange=()=>this.setPage()
            document.querySelectorAll('.link').forEach(node=>{
                node.addEventListener('click',(e)=>{
                    // <a> 标签的 href 属性用于指定超链接目标的 URL。
                    // path name 就是a标签href 跟着的路径
                    // location hash 就是#后面跟着的
                    location.hash=node.pathname
                
                    // 阻止默认行为 取消a标签的默认行为 比方说点击以后a标签的颜色变化了
                    e.preventDefault()
                })
            })
        this.setPage()
        }
        setPage(){
           this.routes.forEach((route)=>{
               route.component.style.display="none"              
           })
        //    没找到的话就是404 数组中最后一个
           let route=this.routes.find(route=>'#'+route.path===location.hash) 
           route.component.style.display="block"
        }
    }
// 建立一个路由关系对应表
new Router({
  mode:"hash",
  routes:[
  {
        path:'/',
        component:document.getElementById('home')
    },
   {
        path:'/b',
        component:document.getElementById('a')
    },
    {
        path:'/c',
        component:document.getElementById('c')
    }
    ]
  

})
</script>
</body>
</html>
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享