<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>原生JS实现Vue History路由</title>
</head>
<body>
<div id="app">
<nav>
<a href="/">首页</a>
<a href="/about">关于</a>
<a href="/contact">联系我们</a>
</nav>
<div id="router-view"></div>
</div>
<script>
const routes = {
'/': '<h1>首页内容</h1>',
'/about': '<h1>关于我们</h1><p>这是关于页面</p>',
'/contact': '<h1>联系我们</h1><p>电话:123456789</p>',
'*': '<h1>404 页面不存在</h1>'
};
const router = {
currentPath: window.location.pathname,
init() {
console.log(123)
this.render();
window.addEventListener('popstate', () => {
this.currentPath = window.location.pathname;
this.render();
});
document.querySelectorAll('a').forEach(link => {
link.addEventListener('click', (e) => {
e.preventDefault();
const path = link.getAttribute('href');
this.navigate(path);
});
});
},
navigate(path) {
history.pushState(null, null, path);
this.currentPath = path;
this.render();
},
render() {
const routerView = document.getElementById('router-view');
const content = routes[this.currentPath] || routes['*'];
routerView.innerHTML = content;
}
};
router.init();
</script>
</body>
</html>