spa单页面应用,主要两种实现方式,history和hash。通过js操作浏览器bom中的history和location.hash对象实现页面的切换跳转。
history模式
<div id="app"><a class="route a">pageA</a><a class="route a">pageB</a></div>
<script>// 注册路由document.querySelectorAll(".route").forEach(route => {route.addEventListener('click', (e) => {e.preventDefault();let link = route.textContent;window.history.pushState({ name: 'route' }, link + "title", link);})})// 监听路由window.addEventListener('popstate', (e) => {console.log({location: location.href,state: e.state});})</script>
通过window下的history对象的pushState设置路由,可以看到浏览器的地址栏发生路径切换。
点击浏览器的前进和后退按钮,此时可触发监听路由事件,通过popstate的方法进行监听。
由此实现前端路由的切换。
hash模式
第二种前端路由切换模式
<div id="app"><a class="hash a">/pageA</a><a class="hash a">/pageB</a></div>
<script>// 注册路由document.querySelectorAll(".hash").forEach(route => {route.addEventListener('click', (e) => {e.preventDefault();let link = route.textContent;location.hash = link}, false);})// 监听路由window.addEventListener('hashchange', (e) => {console.log({location: location.href,hash: location.hash});})</script>
通过location.hash进行页面跳转,并通过hashchange事件进行监听。
可以实现前端页面的路由跳转
