不用vue实现切换路由
使用原生 JavaScript 实现路由切换
通过监听 URL 变化并动态加载内容,可以无需 Vue 或其他框架实现路由切换。核心是利用 window.history API 和 popstate事件。
// 定义路由配置
const routes = {
'/': 'Home Page Content',
'/about': 'About Page Content',
'/contact': 'Contact Page Content'
};
// 渲染当前路由内容
function renderRoute() {
const path = window.location.pathname;
document.getElementById('app').innerHTML = routes[path] || '404 Not Found';
}
// 监听浏览器前进/后退
window.addEventListener('popstate', renderRoute);
// 初始化路由
document.addEventListener('DOMContentLoaded', () => {
document.body.addEventListener('click', e => {
if (e.target.matches('[data-link]')) {
e.preventDefault();
const href = e.target.getAttribute('href');
window.history.pushState(null, null, href);
renderRoute();
}
});
renderRoute();
});
基于 Hash 的路由实现
对于不支持 History API 的旧浏览器,可以使用 hash 路由模式:

const routes = {
'#/': 'Home Page',
'#/about': 'About Page',
'#/contact': 'Contact Page'
};
function handleHashChange() {
const hash = window.location.hash || '#/';
document.getElementById('app').innerHTML = routes[hash] || '404';
}
window.addEventListener('hashchange', handleHashChange);
window.addEventListener('load', handleHashChange);
动态内容加载方案
如果需要从服务器加载内容而非静态文本:

async function loadRouteContent(path) {
try {
const response = await fetch(`/api/content${path}`);
return await response.text();
} catch (error) {
return 'Error loading content';
}
}
async function renderDynamicRoute() {
const path = window.location.pathname;
const content = await loadRouteContent(path);
document.getElementById('app').innerHTML = content;
}
路由参数处理
实现带参数的路由匹配:
const routes = [
{ pattern: /^\/user\/(\w+)$/, handler: id => `User Profile: ${id}` },
{ pattern: /^\/post\/(\d+)$/, handler: id => `Post ID: ${id}` }
];
function matchRoute() {
const path = window.location.pathname;
for (const route of routes) {
const match = path.match(route.pattern);
if (match) {
return route.handler(...match.slice(1));
}
}
return '404 Not Found';
}
路由守卫实现
添加路由切换前的权限检查:
const auth = {
isAuthenticated: false
};
function navigateTo(path) {
if (path === '/admin' && !auth.isAuthenticated) {
window.location.pathname = '/login';
return;
}
window.history.pushState(null, null, path);
renderRoute();
}
这些方案提供了从简单到进阶的路由实现方式,可根据项目需求选择或组合使用。核心思路都是通过监听 URL 变化并更新 DOM,无需依赖任何前端框架。






