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应用的包管理器,它擅长 ...
随机推荐
- forEach、for in、for of三者区别
forEach更多的用来遍历数组for in 一般常用来遍历对象或jsonfor of数组对象都可以遍历,遍历对象需要通过和Object.keys()for in循环出的是key,for of循环出的 ...
- is == id ,编码
一. id 查询内存地址. # name = 'alex' # print(id(name)) # name1 = 'alex' # name2 = 'alex' # print(name1 == n ...
- loj10153二叉苹果树
有一棵二叉苹果树,如果数字有分叉,一定是分两叉,即没有只有一个儿子的节点.这棵树共 N 个节点,标号 1 至 N,树根编号一定为 1. 我们用一根树枝两端连接的节点编号描述一根树枝的位置.一棵有四根树 ...
- Docker系列(一)Docker概述,核心概念讲解,安装部署
部分内容参考链接: Docker实战总结(非常全面,建议收藏) 一. Docker概述 Docker是一个开源的应用容器引擎(基于Go语言开发),让开发者可以打包他们的应用以及依赖包到一个可移植的容器 ...
- Django(orm)转
转载自 https://www.jianshu.com/p/d92ecd3644f7?utm_campaign=hugo&utm_medium=reader_share&utm_con ...
- Aruba无线控制器常用操作
初始配置 1.console到初始化的无线控制器上 Enter System name [Aruba7005]: Enter VLAN 1 interface IP address [172.16.0 ...
- 19.损坏磁盘阵列及修复&磁盘阵列+备份盘
1.在确认有一块物理硬盘设备出现损坏而不能继续正常使用后,应该使用mdadm 命令将其移除,然后查看RAID 磁盘阵列的状态,可以发现状态已经改变. [root@Centos ~]# mdadm /d ...
- 小白搭建WNMP详细教程---NGINX、MYSQL、PHP的整合配置
我自定义安装后的目录结构如下: 安装在D盘的WNMP下,其中WWW是网站的目录.ZIPS是放压缩包文件. 一.配置环境变量 在桌面右击我的电脑,选择属性,出现窗口后,按下图所示操作: 点击编辑后,会出 ...
- Java反射开窍--1
1.通过案例引出反射并体会反射的好处 案例:美团外卖 --->付款 --->要么用微信支付 要么用支付宝支付 package com.zhaoss.test01; //接口的制定方:美团外 ...
- 设计模式(七)——适配器模式(SpringMVC框架分析)
适配器模式 1 现实生活中的适配器例子 泰国插座用的是两孔的(欧标),可以买个多功能转换插头 (适配器) ,这样就可以使用了. 2 基本介绍 1) 适配器模式(Adapter Pattern)将某个类 ...