
使用 vue router 实现 history 路由
问题中描述了使用 History 路由进行页面切换的需求,无需在每个页面重复编写公共代码。这里提供了一种利用 Vue Router 和 jQuery 的解决方案:
<head>
<!-- 引入 Vue、Vue 路由和 jQuery 库 -->
<script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router@3.5.4/dist/vue-router.js"></script>
<script src="https://unpkg.com/jquery@3.6.0/dist/jquery.js"></script>
</head>
<body>
<!-- 公共内容 -->
<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 路由实例
const router = new VueRouter({ mode: 'history', routes: routes });
// 导航守卫,用于在切换路由时加载页面内容
router.beforeEach(function (to, from, next) {
// 移除旧页面
$('#route-view').empty();
// 加载新页面
$('#route-view').load(to.meta.template);
next(true);
});
// 将路由实例挂载到全局,便于子页面使用
window.$router = router;
// 点击按钮切换路由
$('#menuA').on('click', function() { $router.push({ name: 'PageA' }) });
$('#menuB').on('click', function() { $router.push({ name: 'PageB' }) });
</script>
</body>子页面代码:
<!-- page-a.html --> <div>我是页面 A</div> <!-- page-b.html --> <div>我是页面 B</div>
使用方法:
通过这种方式,可以实现 History 路由,在切换页面时动态加载子页面的内容,并避免重复编写公共代码。
立即学习“前端免费学习笔记(深入)”;
以上就是如何使用 Vue Router 和 jQuery 实现 History 路由,避免页面切换时重复加载公共代码?的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号