js web简单的路由管理器
灵感来自此博客和此库
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简单的路由管理器的更多相关文章
- 04 Vue Router路由管理器
路由的基本概念与原理 Vue Router Vue Router (官网: https://router.vuejs.org/zh/)是Vue.js 官方的路由管理器. 它和vue.js的核心深度集成 ...
- Vue Router路由管理器介绍
参考博客:https://www.cnblogs.com/avon/p/5943008.html 安装介绍:Vue Router 版本说明 对于 TypeScript 用户来说,vue-router@ ...
- JS模块规范 前端模块管理器
一:JS模块规范(为了将js文件像java类一样被import和使用而定义为模块, 组织js文件,实现良好的文件层次结构.调用结构) A:CommonJS就是为JS的表现来制定规范,因为js没有模块的 ...
- Vue.js路由管理器 Vue Router
起步 HTML <script src="https://unpkg.com/vue/dist/vue.js"></script> <script s ...
- java web 简单的权限管理
spring ,springMvc ,mybatis 简单权限管理 其实只需要3张表..admin_group ,function,group 表
- vue-router路由管理器
安装vue-router npm install vue-router 在main.js中引入 import VueRouter from 'vue-router' Vue.use(VueRouter ...
- npm --- Node.js包管理器
目录 1. 安装Node.js 2. 运行npm 3. npm介绍 3.1 安装插件 3.2 更新插件 3.3 卸载插件 3.4 查看当前目录中的插件列表 4. 使用cnpm 4.1 安装 npm( ...
- Vue路由管理之Vue-router
一.Vue Router介绍 Vue Router 是 Vue.js 官方的路由管理器.它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌.包含的功能有: 嵌套的路由/视图表 模块化的. ...
- 包管理器Bower使用手冊之中的一个
包管理器Bower使用手冊之中的一个 作者:chszs,转载需注明.博客主页:http://blog.csdn.net/chszs 一.Bower介绍 Bower是一个适合Web应用的包管理器,它擅长 ...
随机推荐
- .NET5 它来了!微软大一统时代来临!
今天双11,Microsoft released.NET 5(在他们的开发博客上同时发布).新版本的重点是改进.NET Core 3.1: 更小的单文件应用程序.对 Windows ARM64的支持以 ...
- 日记 + sb错误
置顶消息cpdd 1.29 完了,文化课没了 我是废物 1.28 更新了自己的副标题 前副标题:Future never has to do with past time,but present ti ...
- Mysql数据库版本高低引起的group by问题
低版本的Mysql,group by限制性比较小,在进行group by时,select的对象可包含多个,但是换成高版本5.6以上好像,使用group by 以后,select的对象必须也已经被聚合, ...
- typedef void (*sighandler_t)(int);
typedef void (*sighandler_t)(int); sighandler_t signal(int signum, sighandler_t handler); ---------- ...
- 获取java栈异常
package com.loan.modules.extbiz.in.rabbitmq.util; import java.io.PrintWriter; import java.io.StringW ...
- Spring 事务、异步和循环依赖有什么关系?
前言 在循环依赖中有一种循环依赖,就是自注入:自己依赖自己. 事务的自注入 在 Spring 自调用事务失效,你是怎么解决的? 有小伙伴提出可以自己注入自己来解决事务失效. 具体使用方式如下: @Sl ...
- ApiTesting全链路自动化测试框架 - 初版发布(一)
简介 此框架是基于Python+Pytest+Requests+Allure+Yaml+Json实现全链路接口自动化测试. 主要流程:解析接口数据包 ->生成接口基础配置(yml) ->生 ...
- PHP基础之与MySQL那些事
前言 这篇文章会对PHP的MySQL扩展库,MySQLI的扩展库,SQL批量执行,事务控制等等进行一些简单的讲解. MySQL扩展 PHP中MySQL扩展,虽然因为安全的原因,在PHP5.6及往上不在 ...
- Spring学习笔记2
一.什么是AOP 面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术.在不影响原来功能代码的基础上,使用动态代理加入自己需要的一些功能(比如权限的验证,事务的控制,日志的记录 ...
- js--执行上下文和作用域相关问题
前言 如果你是或者你想成为一名合格的前端开发工作者,你必须知道JavaScript代码在执行过程,知道执行上下文.作用域.变量提升等相关概念,并且熟练应用到自己的代码中.本文参考了你不知道的JavaS ...