
为纯 html 网页实现 history 路由
需求分析
需要根据 URL 访问不同页面的内容,显示在“div#route-view”中,同时保持公共代码不变。
解决方案:使用 Vue Router + jQuery
- 引入 Vue、Vue Router 和 jQuery 库。
- 定义 Vue 路由配置(routes),其中 path 为需要访问的页面,meta 包含页面模板的路径。
- 创建 Vue Router 路由器并挂载到 Vue 实例上。
- 在路由切换之前,移除旧页面并加载新页面。
代码示例
立即学习“前端免费学习笔记(深入)”;
主页 index.html
<div id="route-view"></div>
<script>
// 定义 Vue 路由配置
const routes = [{
path: '/a',
meta: {
template: '/subpages/page-a.html'
}
}, {
path: '/b',
meta: {
template: '/subpages/page-b.html'
}
}];
// 创建 Vue 路由路由器
const router = new VueRouter({ routes: routes });
// 路由切换之前,移除旧页面并加载新页面
router.beforeEach((to, from, next) => {
$('#route-view').empty();
$('#route-view').load(to.meta.template);
next(true);
});
// 挂载路由器到全局
window.$router = router;
</script>子页面 page-a.html、page-b.html
<!-- page-a.html --> <div>我是页面 A</div> <!-- page-b.html --> <div>我是页面 B</div>
使用方法
通过按钮点击或者直接输入 URL 来切换页面,例如:
- 点击按钮“切换到 A”:$router.push({ name: 'PageA' })
- 直接访问 URL “http://example.com/a”
注意:
在生产环境中,需要配置 Web 服务器以支持 History Mode。











