灵感来自此博客此库

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. Python中,单引号,双引号,三引号的使用区别与原因

    先说1双引号与3个双引号的区别,双引号所表示的字符串通常要写成一行如:s1 = "hello,world"如果要写成多行,那么就要使用/ ("连行符")吧,如s ...

  2. 洛谷 P4999

    题目链接: P4999 烦人的数学作业 题目大意 详见题目 solution 有一个显而易见的结论 发现 \(ans_{l, r} = ans_{1. r} - ans_{1, l - 1}\) 那只 ...

  3. 转载,Pandas 数据统计用法

    pandas模块为我们提供了非常多的描述性统计分析的指标函数,如总和.均值.最小值.最大值等,我们来具体看看这些函数: 1.随机生成三组数据import numpy as npimport panda ...

  4. 希尔伯特曲线python3实现

    需要OpenGL库:https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyopengl #coding:utf-8 from OpenGL.GL import * ...

  5. msf+cobaltstrike联动(二):把cs中的机器spwan给msf

    前提:CS已经获取到session,可以进入图形化管理机器,现在需要使用msf进行进一步渗透,需要msf的metepreter. 开启msf msf设置监听 msf > use exploit/ ...

  6. xss原理及简单介绍

    XSS简单介绍-Web攻击 一 ·基础介绍 xss表示Cross Site Scripting(跨站脚本攻击),它与SQL注入攻击类似,SQL注入攻击中以SQL语句作为用户输入,从而达到查询/修改/删 ...

  7. Flink-v1.12官方网站翻译-P022-Working with State

    有状态程序 在本节中,您将了解Flink为编写有状态程序提供的API.请看一下Stateful Stream Processing来了解有状态流处理背后的概念. 带键值的数据流 如果要使用键控状态,首 ...

  8. UI中的事件系统EventSystem

    一.EventSystem简介 用于处理事件的分发和相应的系统,创建画布的同时会创建事件系统 二.UGUI实现事件系统的3种方式 1.使用组件eventTrigger(不推荐),拖动赋值 2.代码添加 ...

  9. 从问题入手,深入了解JavaScript中原型与原型链

    从问题入手,深入了解JavaScript中原型与原型链 前言 开篇之前,我想提出3个问题: 新建一个不添加任何属性的对象为何能调用toString方法? 如何让拥有相同构造函数的不同对象都具备相同的行 ...

  10. codeforces644B. Processing Queries (模拟)

    In this problem you have to simulate the workflow of one-thread server. There are n queries to proce ...