
如何在 javascript 中实现 history 路由
需求:根据访问路径的不同,呈现不同的 html 内容,同时保持公共部分不变。
解决方案:
可以使用 vue-router 来实现:
立即学习“前端免费学习笔记(深入)”;
示例代码:
<!-- 主页 -->
<div>
我是公共部分
<button id="menuA">切换到 A</button>
<button id="menuB">切换到 B</button>
</div>
<div id="route-view"></div>
<script>
// 路由配置
const routes = [
{
name: 'PageA',
path: '/a',
meta: {
template: '/subpages/page-a.html',
},
},
{
name: 'PageB',
path: '/b',
meta: {
template: '/subpages/page-b.html',
},
},
];
// 创建 Vue-Router 实例
const router = new VueRouter({ mode: 'history', routes });
// 在 beforeEach 钩子函数中加载子页面模板
router.beforeEach((to, from, next) => {
$('#route-view').empty();
$('#route-view').load(to.meta.template);
next(true);
});
// 挂载到全局
window.$router = router;
</script>
<script>
// 按钮点击事件,跳转路由
$('#menuA').on('click', () => $router.push({ name: 'PageA' }));
$('#menuB').on('click', () => $router.push({ name: 'PageB' }));
</script>效果:
访问不同的路由路径,即可看到不同的子页面内容,同时公共部分保持不变。
以上就是如何在 Vue.js 中使用 History 路由实现根据路径展示不同内容和保持公共部分不变?的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号