Hasi route jump implementation

The history route jump of h5 has been realized before, here is another Hassi route

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
    <div>
      <a href="#/">首页</a>
      <a href="#/home">home</a>
      <a href="#/about">about</a>
      <div id="root"></div>
    </div>
</body>
<script>

  class Router {
    
    
    constructor({
    
    route}) {
    
    
      this.route = route;
      this.root = document.getElementById('root');
      this.init()
    }
    init() {
    
    
      // hashchange事件监听url#/的变化
      window.addEventListener('hashchange', () => {
    
    
        let topath = window.location.hash.slice(1)
        this.updateDom(topath)
      })
      // 监听浏览器刷新
      window.addEventListener('load', () => {
    
    
        let topath = window.location.hash.slice(1);
        this.updateDom(topath)
      })
    }
    updateDom(topath) {
    
    
      let Iner = this.route.filter(item => item.path === topath)[0].component;
      this.root.innerHTML = Iner
    }
  }

  new Router({
    
    
    route: [
      {
    
    
        path: '/',
        component: '首页'
      },
      {
    
    
        path: '/home',
        component: 'home'
      },
      {
    
    
        path: '/about',
        component: 'about'
      }
    ]
  })
</script>
</html>

Guess you like

Origin blog.csdn.net/srTres/article/details/109414106