vue-router的简单实现原理

<!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>
  <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
  <a href="#/a">aaa</a>
  <a href="#/b">bbb</a>
  <a href="#/c">ccc</a>
  <div id="box">

  </div>
  <script>
    let routes = [{
        path: '/a',
        component: './tem/a.html',
        childre:[
          {
            path:"b",
            component:'./img/off.png'
          }
        ]
      },
      {
        path: '/b',
        component: './tem/b.html'
      },
      {
        path: '/c',
        component: './tem/c.html'
      },
    ]
    let cache = {};
    // 建立缓存
    addEventListener('hashchange', () => {
      let hash = location.hash.replace('#', '')
      // 拿到hash值
     let flag = routes.some((item) => {
        if (item.path === hash) {
          if (cache[hash]) {
            $('#box').html(cache[hash]);
          } else {
            $.ajax(item.component).then((res) => {
              cache[hash] = res;
              $('#box').html(res);
            })
          }
          return true;
        }
        return false;
      })
      if(!flag){
          $('body').html('404')
      }
    })

  </script>
</body>

</html>

猜你喜欢

转载自www.cnblogs.com/l8l8/p/9392298.html