返回
前端路由详解:掌握面试必备核心原理
前端
2023-09-12 09:44:37
Hash 模式实现
实现原理
Hash 模式依赖于 URL 的 hash(即 # 后面的部分)。改变 hash 不会触发页面刷新。通过监听 hashchange
事件,可以实现在不同路径间切换而不重新加载整个页面。
示例代码
window.addEventListener('hashchange', function() {
const currentPath = window.location.hash.slice(1) || '/';
// 路由表
const routes = {
'/home': () => console.log("显示首页"),
'/about': () => console.log("显示关于我们页面")
};
const handleRoute = (path) => {
if (routes[path]) {
return routes[path]();
}
// 如果找不到匹配的路由,则重定向到404页
window.location.hash = '#/not-found';
};
handleRoute(currentPath);
});
// 手动触发一次,确保页面加载时正确渲染当前路径的内容
window.dispatchEvent(new HashChangeEvent('hashchange'));
安全建议
- 确保所有路由处理函数中执行的操作都是安全的。避免在客户端暴露敏感信息。
- 考虑使用中间件模式,在路由匹配前进行身份验证和授权检查。
History 模式实现
实现原理
History API 提供了 pushState
和 replaceState
方法,可以改变浏览器地址栏中的 URL,而无需重新加载页面。通过监听 popstate
事件来检测用户是否通过浏览历史记录(如后退和前进按钮)触发路径变化。
示例代码
const routes = {
'/home': () => console.log("显示首页"),
'/about': () => console.log("显示关于我们页面")
};
window.addEventListener('popstate', function(event) {
const currentPath = window.location.pathname;
if (routes[currentPath]) {
routes[currentPath]();
} else {
// 重定向到404页
history.pushState({}, '', '/not-found');
}
});
function navigateTo(path) {
if (!path.startsWith('/')) path = '/' + path;
history.pushState({ path }, '', path);
if (routes[path]) {
routes[path]();
} else {
// 处理404
history.replaceState({}, '', '/not-found');
console.log('404: 页面未找到');
}
}
// 初始页面加载时,也需触发路由匹配
navigateTo(window.location.pathname);
// 示例:导航到某个路径
document.getElementById('home-link').addEventListener('click', function(e) {
e.preventDefault();
navigateTo('/home');
});
安全建议
- 使用 History API 时,必须在服务器端配置合适的重定向规则,确保直接访问如
/about
能够正确响应。 - 注意处理好404状态码的显示和用户提示。
结论
前端路由是现代 Web 应用中不可或缺的一部分。通过使用 Hash 或 History 模式,开发者可以在不刷新页面的情况下实现应用内部导航。掌握这两种模式的基本原理,能帮助开发者在面试时更好地展示自己对前端技术的理解。同时,注意安全性和用户体验的优化也是关键。