JS实现路由的关键是监听URL变化并动态更新页面内容,主要有hash和History API两种方式。1. Hash路由通过监听window.onhashchange事件获取location.hash值,根据不同的hash值渲染对应页面内容,兼容性好但URL中带有#,影响美观。2. History API路由利用history.pushState和replaceState修改URL,结合onpopstate监听前进后退操作,URL更简洁,但需服务器配置支持,防止刷新时404。两种方式均可通过解析URL参数实现传参,如hash中分割字符串或使用URLSearchParams解析查询参数。为避免刷新导致路由失效,服务器需将所有路由重定向到index.html。此外,可使用React Router等第三方库简化开发,支持嵌套路由、路由守卫等高级功能,提升开发效率。
JS实现路由,本质上就是根据不同的URL显示不同的内容。关键在于监听URL变化并更新页面。
解决方案
JS实现路由主要有两种方式:一种是利用
hash
history
Hash路由
Hash路由的原理是监听
window.onhashchange
#
location.hash
window.onhashchange = function() { const hash = location.hash.slice(1); // 去掉#号 updatePage(hash); }; function updatePage(hash) { // 根据hash值更新页面内容 const contentDiv = document.getElementById('content'); switch (hash) { case 'home': contentDiv.innerHTML = '<h1>Home Page</h1><p>Welcome to the home page.</p>'; break; case 'about': contentDiv.innerHTML = '<h1>About Page</h1><p>This is the about page.</p>'; break; case 'contact': contentDiv.innerHTML = '<h1>Contact Page</h1><p>Contact us here.</p>'; break; default: contentDiv.innerHTML = '<h1>404 Not Found</h1><p>Page not found.</p>'; } } // 页面加载时初始化 if (location.hash) { updatePage(location.hash.slice(1)); } else { location.hash = 'home'; // 默认显示home }
Hash路由的优点是兼容性好,即使在老版本的浏览器上也能正常工作。缺点是URL中会有一个
#
History API路由
History API路由使用
history.pushState
history.replaceState
window.onpopstate
function navigateTo(url) { history.pushState(null, null, url); updatePage(url); } window.onpopstate = function() { updatePage(location.pathname); }; function updatePage(url) { // 根据url更新页面内容 const contentDiv = document.getElementById('content'); switch (url) { case '/': contentDiv.innerHTML = '<h1>Home Page</h1><p>Welcome to the home page.</p>'; break; case '/about': contentDiv.innerHTML = '<h1>About Page</h1><p>This is the about page.</p>'; break; case '/contact': contentDiv.innerHTML = '<h1>Contact Page</h1><p>Contact us here.</p>'; break; default: contentDiv.innerHTML = '<h1>404 Not Found</h1><p>Page not found.</p>'; } } // 页面加载时初始化 updatePage(location.pathname); // 绑定链接点击事件 (假设有 <a href="/about">About</a> 这样的链接) document.addEventListener('click', function(event) { if (event.target.tagName === 'A') { event.preventDefault(); // 阻止默认的链接跳转 const url = event.target.getAttribute('href'); navigateTo(url); } });
History API路由的优点是URL更美观,没有
#
在Hash路由中,如果
location.hash
default
在使用History API路由时,服务器端也需要配置。当服务器收到一个不在预定义的路由表中的请求时,应该返回
index.html
在Hash路由中,参数通常会附加在
#
#product/123
location.hash
const hash = location.hash.slice(1); const parts = hash.split('/'); const route = parts[0]; // "product" const id = parts[1]; // "123"
在使用History API路由时,参数可以直接附加在URL中,例如
/product/123?color=red
URLSearchParams
const urlParams = new URLSearchParams(location.search); const color = urlParams.get('color'); // "red"
在使用History API路由时,如果直接刷新页面,服务器可能会返回404错误。为了避免这种情况,需要在服务器端配置,将所有未知的路由都重定向到
index.html
const express = require('express'); const path = require('path'); const app = express(); app.use(express.static('public')); // 假设静态文件在public目录下 app.get('*', (req, res) => { res.sendFile(path.resolve(__dirname, 'public', 'index.html')); }); app.listen(3000, () => { console.log('Server listening on port 3000'); });
这段代码会将所有GET请求都重定向到
index.html
有很多优秀的第三方库可以简化JS路由的实现,例如
React Router
Vue Router
Angular Router
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; function App() { return ( <Router> <div> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> <li> <Link to="/users">Users</Link> </li> </ul> </nav> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> <Route path="/users" component={Users} /> </div> </Router> ); }
这段代码使用
BrowserRouter
Route
Link
以上就是JS如何实现路由功能的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号