1. 程式人生 > >vue-router的簡單實現原理

vue-router的簡單實現原理

lan type script min cal ont document .ajax scale

<!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>

vue-router的簡單實現原理