Implement simple route Manually implement hash routes in vUE

The idea is to create a constructor that maps the path in Routes to the hash in location. Cons: No redirection and jump handling for errors to update

<! DOCTYPEhtml>
<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="Chen Rubin">
    <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="/">Home page</a>
      <a class="link" href="/b">B page</a>
      <a class="link" href="/c">C page</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>This is page C</p>
    </section>
    
<script>    
// Map the hash of location to the path in the route to switch the route page
    class Router {
        constructor({mode,routes}){
            this.routes=routes
            // The method that fires when the hash is changed
            // 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) = >{
                    // The href attribute of the  tag is used to specify the URL of the hyperlink target.
                    // Path name is the path that the a tag href follows
                    // Location hash is what follows #
                    location.hash=node.pathname
                
                    Cancel the default behavior of the A TAB. For example, the color of the A TAB changes after the click
                    e.preventDefault()
                })
            })
        this.setPage()
        }
        setPage(){
           this.routes.forEach((route) = >{
               route.component.style.display="none"              
           })
        // This is the last item in the 404 array
           let route=this.routes.find(route= >The '#'+route.path===location.hash) 
           route.component.style.display="block"}}// Create a routing relationship mapping table
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>
Copy the code