
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错误。











