不用vue实现切换路由
使用原生 JavaScript 实现路由切换
通过监听 URL 变化并动态加载内容,可以实现简单的路由切换功能。以下是一个基于 history.pushState 和 popstate 事件的实现方式:
// 定义路由配置
const routes = {
'/': '<h1>Home Page</h1>',
'/about': '<h1>About Page</h1>',
'/contact': '<h1>Contact Page</h1>'
};
// 获取内容容器
const contentDiv = document.getElementById('content');
// 初始化路由
function navigateTo(path) {
window.history.pushState({}, path, window.location.origin + path);
renderContent(path);
}
// 渲染内容
function renderContent(path) {
contentDiv.innerHTML = routes[path] || '<h1>404 Not Found</h1>';
}
// 监听浏览器前进/后退
window.addEventListener('popstate', () => {
renderContent(window.location.pathname);
});
// 初始加载
renderContent(window.location.pathname);
使用 Hash 模式实现路由
对于不支持 HTML5 History API 的旧浏览器,可以使用 hash 路由模式:

const routes = {
'#/': '<h1>Home Page</h1>',
'#/about': '<h1>About Page</h1>',
'#/contact': '<h1>Contact Page</h1>'
};
function handleHashChange() {
const hash = window.location.hash || '#/';
document.getElementById('content').innerHTML = routes[hash] || '<h1>404 Not Found</h1>';
}
// 初始加载和监听变化
window.addEventListener('load', handleHashChange);
window.addEventListener('hashchange', handleHashChange);
使用动态内容加载
如果需要从服务器加载内容,可以修改渲染函数:

async function renderContent(path) {
try {
const response = await fetch(`/api/content${path}`);
const html = await response.text();
contentDiv.innerHTML = html;
} catch (error) {
contentDiv.innerHTML = '<h1>Error loading content</h1>';
}
}
添加路由守卫功能
实现类似 Vue Router 的导航守卫:
const beforeHooks = [];
function beforeEach(callback) {
beforeHooks.push(callback);
}
async function navigateTo(path) {
let allowNavigation = true;
for (const hook of beforeHooks) {
const result = await hook(path);
if (result === false) {
allowNavigation = false;
break;
}
}
if (allowNavigation) {
window.history.pushState({}, path, window.location.origin + path);
renderContent(path);
}
}
完整的路由类实现
封装一个更完整的路由解决方案:
class SimpleRouter {
constructor() {
this.routes = {};
this.beforeHooks = [];
this.contentElement = document.getElementById('content');
window.addEventListener('popstate', () => this.render());
window.addEventListener('load', () => this.render());
}
addRoute(path, content) {
this.routes[path] = content;
}
beforeEach(callback) {
this.beforeHooks.push(callback);
}
async navigate(path) {
let allowNavigation = true;
for (const hook of this.beforeHooks) {
const result = await hook(path);
if (result === false) allowNavigation = false;
}
if (allowNavigation) {
window.history.pushState({}, path, window.location.origin + path);
this.render();
}
}
render() {
const path = window.location.pathname;
this.contentElement.innerHTML = this.routes[path] || '<h1>404 Not Found</h1>';
}
}
// 使用示例
const router = new SimpleRouter();
router.addRoute('/', '<h1>Home Page</h1>');
router.addRoute('/about', '<h1>About Page</h1>');
这些方法提供了从简单到相对完整的路由实现方案,可以根据项目需求选择适合的方式或进行组合扩展。






