
js中实现history路由
要根据访问路径的不同,动态呈现不同HTML内容,可以使用js中的vue-router库。具体实现步骤如下:
安装vue-router:npm install vue-router。定义路由规则:
const routes = [{ name: 'PageA', path: '/a', meta: { template: '/subpages/page-a.html' }}, { name: 'PageB', path: '/b', meta: { template: '/subpages/page-b.html' }}];
创建VueRouter实例:
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;
在页面中添加按钮,用于切换路由:
注意:History Mode需要后端Web服务进行配置,否则刷新页面会出现404错误。
以上就是如何使用 Vue-router 在 JS 中实现动态 HTML 页面切换?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1556534.html
微信扫一扫
支付宝扫一扫