<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>js - router</title> </head> <body> <ul> <!-- 定义路由 --> <li><a href="#/home">home</a></li> <li><a href="#/about">about</a></li> <!-- 渲染路由对应的 UI --> <div id="routeView"></div> </ul> <!-- 不同场景下引入对应文件 --> <!-- <script src="hash.js"></script> --> <!-- <script src="history.js"></script> --> </body> </html>
// 维护 UI 页面 let routerView = null; // 路由变化时,根据路由渲染对应的 ui 页面 function onHashChange() { switch (window.location.hash) { case ‘‘: case ‘#/home‘: routerView.innerHTML = ‘Home‘; return ; case ‘#/about‘: routerView.innerHTML = ‘About‘; break; default: break; } } // 页面加载完不会触发 hashchange,这里主动触发一次 hashchange 事件。 window.addEventListener(‘DOMContentLoaded‘, () => { routerView = document.querySelector(‘#routeView‘); onHashChange(); }) // 监听路由变化。 window.addEventListener(‘hashchange‘, onHashChange);
// 维护 UI 页面。 let routerView = null; // 路由变化时,根据路由渲染对应 UI 页面。 function onPopState() { switch (window.location.pathname) { case ‘/‘: case ‘/home‘: routerView.innerHTML = ‘Home‘; return ; case ‘/about‘: routerView.innerHTML = ‘About‘; break; default: break; } } // 页面加载完不会触发 onPopState, 这里主动触发一次 onPopState 事件。 window.addEventListener(‘DOMContentLoaded‘, () => { routerView = document.querySelector(‘#routeView‘); // 刷新页面。 onPopState(); // 拦截 <a> 标签点击事件默认行为, 点击时使用 pushState 修改 URL并更新手动 UI,从而实现点击链接更新 URL 和 UI 的效果。 let links = document.querySelectorAll(‘a[href]‘); links.forEach(el => { el.addEventListener(‘click‘, e => { e.preventDefault(); // 手动拦截 window.history.pushState(null, ‘‘, el.getAttribute(‘href‘)); onPopState(); }) }) }) // 监听路由变化。 window.addEventListener(‘popstate‘, onPopState);
原文:https://www.cnblogs.com/cc-freiheit/p/12966157.html