
为纯 html 网页实现 history 路由
需求分析
需要根据 URL 访问不同页面的内容,显示在“div#route-view”中,同时保持公共代码不变。
解决方案:使用 Vue Router + jQuery
代码示例
立即学习“前端免费学习笔记(深入)”;
主页 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 来切换页面,例如:
注意:
在生产环境中,需要配置 Web 服务器以支持 History Mode。
以上就是如何使用 Vue Router 和 jQuery 实现纯 HTML 网页的 History 路由需求?的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号