灵感来自此博客此库

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="root"></div>
<template id="home">
<h1>home</h1>
</template>
<template id="about">
<h1>about</h1>
</template>
<template id="dog">
<h1>dog</h1>
</template>
<template id="notFound">
<h1>404 not found</h1>
</template>
<script src="./aja-router.js"></script>
<script>
const router = new AjaRouter();
router.forRoot([
{
path: "",
redirectTo: "home"
},
{
path: "home",
render(host) {
const t = document.querySelector("#home");
host.append(document.importNode(t.content, true));
}
},
{
path: "about",
render(host) {
const t = document.querySelector("#about");
host.append(document.importNode(t.content, true));
}
},
{
path: "dog/:id",
render(host, route) {
const t = document.querySelector("#dog");
const dog = document.importNode(t.content, true);
dog.querySelector(
"h1"
).innerHTML = `dog, id is ${route.params.id.value}`;
host.append(dog);
}
},
{
path: "**",
render(host) {
const t = document.querySelector("#notFound");
host.append(document.importNode(t.content, true));
}
}
]); setTimeout(() => {
router.push("about");
}, 1200);
</script>
</body>
</html>

aja-router.js

const _textIsDynamicRouteExp = /\/?:[a-zA-Z]+/;
class AjaRouter {
_host = document.querySelector("#root");
_routes = []; constructor(host) {
if (host) this._host = host;
this._setup();
} _setup() {
window.addEventListener("load", e => {
this._render();
}); window.addEventListener("popstate", e => {
this._render();
}); // window.addEventListener("hashchange", e => {
// console.log("hash ");
// });
} forRoot(routes = []) {
this._routes = routes.map(route => {
const { path } = route;
const pathSplit = path.split("/");
if (path && path.match(_textIsDynamicRouteExp)) {
route.isDynamic = true;
// 动态路由
const params = {};
let exp = "";
for (var i = 0; i < pathSplit.length; i++) {
const item = pathSplit[i];
let expItem = "/" + item;
if (item.startsWith(":")) {
params[item.replace(/^:/, "")] = { index: i };
expItem = `/(?<${item.replace(/^:/, "")}>[^/]+)`;
}
exp += expItem;
}
if (exp && exp.trim() != "") {
exp = exp.replace(/\//, "");
}
route.exp = new RegExp(exp);
route.params = params;
} return route;
});
} _findHashRoute(path) {
const hash = path ?? document.location.hash.replace(/#\/?/, "");
return this._match(hash);
} /**
* 使用path在routes中寻找路由
*/
_match(path) {
// 1, 先找普通路由
let route = this._routes.find(i => i.path === path);
if (route) {
return route;
} // 2, 找动态路由
route = this._routes
.filter(i => i.isDynamic)
.find(i => {
const pattern = "/";
const routeNameSplit = path.split(pattern);
const dynamicRouteNameSplit = i.path.split(pattern);
const equalRouteLength =
routeNameSplit.length == dynamicRouteNameSplit.length;
const match = path.match(i.exp);
if (match && match.groups) {
for (const k in match.groups) {
const param = i.params[k];
param.value = match.groups[k];
}
} return equalRouteLength && match;
}); if (route) {
return route;
} // 3, 都没找到,默认返回404路由
return this._find404Route();
} _find404Route() {
return this._routes.find(i => i.path === "**");
} _render(path) {
const matchRoute = this._findHashRoute(path);
if (matchRoute) {
this._host.innerHTML = "";
if (matchRoute.redirectTo) {
this._render(matchRoute.redirectTo);
} else {
matchRoute.render(this._host, matchRoute);
}
}
} push(path) {
try {
this._render(path);
window.history.pushState({}, document.title, `#/${path}`);
} catch (error) {}
}
}

js web简单的路由管理器的更多相关文章

  1. 04 Vue Router路由管理器

    路由的基本概念与原理 Vue Router Vue Router (官网: https://router.vuejs.org/zh/)是Vue.js 官方的路由管理器. 它和vue.js的核心深度集成 ...

  2. Vue Router路由管理器介绍

    参考博客:https://www.cnblogs.com/avon/p/5943008.html 安装介绍:Vue Router 版本说明 对于 TypeScript 用户来说,vue-router@ ...

  3. JS模块规范 前端模块管理器

    一:JS模块规范(为了将js文件像java类一样被import和使用而定义为模块, 组织js文件,实现良好的文件层次结构.调用结构) A:CommonJS就是为JS的表现来制定规范,因为js没有模块的 ...

  4. Vue.js路由管理器 Vue Router

    起步 HTML <script src="https://unpkg.com/vue/dist/vue.js"></script> <script s ...

  5. java web 简单的权限管理

    spring ,springMvc ,mybatis 简单权限管理 其实只需要3张表..admin_group  ,function,group 表

  6. vue-router路由管理器

    安装vue-router npm install vue-router 在main.js中引入 import VueRouter from 'vue-router' Vue.use(VueRouter ...

  7. npm --- Node.js包管理器

    目录 1. 安装Node.js 2. 运行npm 3. npm介绍 3.1 安装插件 3.2 更新插件 3.3 卸载插件 3.4 查看当前目录中的插件列表 4. 使用cnpm 4.1 安装 npm( ...

  8. Vue路由管理之Vue-router

    一.Vue Router介绍 Vue Router 是 Vue.js 官方的路由管理器.它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌.包含的功能有: 嵌套的路由/视图表 模块化的. ...

  9. 包管理器Bower使用手冊之中的一个

    包管理器Bower使用手冊之中的一个 作者:chszs,转载需注明.博客主页:http://blog.csdn.net/chszs 一.Bower介绍 Bower是一个适合Web应用的包管理器,它擅长 ...

随机推荐

  1. 2021年,python的入门基础-----基础一

    先记录下pycharm编译器相关的信息 1.某些常用快捷键: Ctrl+/ 注释: Tab缩进,shift+Tab; Ctrl+Z 撤销 2.设置界面编辑风格: File>Settings> ...

  2. Jenkins(6)测试报告邮件发送

    前言 前面已经实现在jenkins上展示html的测试报告,接下来只差最后一步,把报告发给你的领导,展示你的劳动成果了. 安装 Email Extension Plugin 插件 jenkins首页- ...

  3. G - 棋盘游戏

    小希和Gardon在玩一个游戏:对一个N*M的棋盘,在格子里放尽量多的一些国际象棋里面的"车",并且使得他们不能互相攻击,这当然很简单,但是Gardon限制了只有某些格子才可以放, ...

  4. Codeforces Round #647 (Div. 2) C. Johnny and Another Rating Drop(数学)

    题目链接:https://codeforces.com/contest/1362/problem/C 题意 计算从 $0$ 到 $n$ 相邻的数二进制下共有多少位不同,考虑二进制下的前导 $0$ .( ...

  5. Educational Codeforces Round 87 (Rated for Div. 2)

    比赛链接:https://codeforces.com/contest/1354 A - Alarm Clock 题意 一个人要睡够 $a$ 分钟,一开始睡 $b$ 分钟后闹钟响铃,之后每次设置 $c ...

  6. hdu 6806 Equal Sentences 找规律

    题意: 给你一个有n个单词的单词串S,对这n个单词进行排列组合形成新的一个单词串T,如果在S中任意某个单词所在位置,和这个单词在T中所在位置之差的绝对值小于等于1,那么就说S和T串相等 让你求S一共有 ...

  7. hdu5534 Partial Tree

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others) Total Submissi ...

  8. 01.原生态jdbc程序中问题总结

    1.数据库启动包配置到工程目录中(mysql5.1) mysql-connector-java-5.1.7-bin.jar 2.jdbc原生态操作数据库(程序) 操作mysql数据库 1 packag ...

  9. C++构造函数、复制函数易错点

    C++中复制函数在三种情况下自动调用: 用一个对象初始化另一个对象 函数的参数为对象 函数的返回值为对象 下面用几个代码片段解释复制函数的调用中的一些常见"坑": 一:默认复制函数 ...

  10. CF1462-F. The Treasure of The Segments

    题意: 给出n个线段组成的集合,第i个线段用 \(\{l_i, r_i\}\) 表示线段从坐标轴的点\(l_i\)横跨到点\(r_i\).现在你可以删除其中的一些线段,使得剩下的线段组成的集合中至少存 ...