
实现历史路由的方法
在提出的需求中,需要根据不同的访问路径,在指定区域呈现不同的 html。而在 javascript 中,实现历史路由的方法是使用vue-router这样一个库。
使用 vue-router 实现
定义路由
立即学习“Java免费学习笔记(深入)”;
定义一个路由数组,其中包含了各个页面的路径和元数据(如页面模板位置)。如下所示:
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: routes });
在路由切换时更新页面内容
router.beforeeach(function (to, from, next) { // 移除旧页面 $('#route-view').empty(); // 加载新页面 $("#route-view").load(to.meta.template); next(true);});
挂载路由到全局对象
window.$router = router;
示例代码
以下是一个示例代码,展示了如何使用 vue-router 实现历史路由:
我是公共部分// 定义路由 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: 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' }) });
我是页面 a
我是页面 B
注意:在使用 history mode 时,需要对后端 web server 进行配置,以支持这种路由模式。否则,在刷新页面时可能会出现 404 错误。
以上就是如何利用 vue-router 在 JavaScript 中实现历史路由?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1630258.html
微信扫一扫
支付宝扫一扫