index.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. import { PAGES, TABS } from "../ctx";
  2. import type { BackOptions, PageInstance, PushOptions } from "../types";
  3. import { storage, last, isNull, isEmpty, get, isFunction, toArray, map, debounce } from "../utils";
  4. // 路由信息类型
  5. type RouteInfo = {
  6. path: string;
  7. meta?: UTSJSONObject;
  8. };
  9. // 跳转前钩子类型
  10. type BeforeEach = (to: RouteInfo, from: PageInstance, next: () => void) => void;
  11. // 登录后回调类型
  12. type AfterLogin = () => void;
  13. // 路由事件集合
  14. type Events = {
  15. beforeEach?: BeforeEach;
  16. afterLogin?: AfterLogin;
  17. };
  18. // 路由核心类
  19. export class Router {
  20. private _events = {} as Events; // 事件存储
  21. // 获取缓存的路由参数
  22. params() {
  23. const data = storage.get("router-params") as UTSJSONObject;
  24. if (isNull(data)) {
  25. return {} as UTSJSONObject;
  26. }
  27. return data;
  28. }
  29. // 获取默认路径,支持 home 和 login
  30. defaultPath(name: "home" | "login") {
  31. const paths = {
  32. home: PAGES[0].path, // 首页为第一个页面
  33. login: "/pages/user/login"
  34. };
  35. return get(paths, name) as string;
  36. }
  37. // 获取当前页面栈的所有页面实例
  38. getPages(): PageInstance[] {
  39. return map(getCurrentPages(), (e) => {
  40. let path = e.route!;
  41. // 根路径自动转为首页
  42. if (path == "/") {
  43. path = this.defaultPath("home");
  44. }
  45. // 补全路径前缀
  46. if (!path.startsWith("/")) {
  47. path = "/" + path;
  48. }
  49. // 获取页面样式
  50. const page = PAGES.find((e) => e.path == path);
  51. const style = page?.style;
  52. const meta = page?.meta;
  53. // 获取页面暴露的方法
  54. // @ts-ignore
  55. let exposed = e.vm as any;
  56. // #ifdef H5
  57. exposed = get(e, "vm.$.exposed");
  58. // #endif
  59. // 获取页面 query 参数
  60. const query = (get(e, "options") ?? {}) as UTSJSONObject;
  61. return {
  62. path,
  63. // @ts-ignore
  64. vm: e.vm!,
  65. // @ts-ignore
  66. exposed,
  67. style,
  68. meta,
  69. query,
  70. isCustomNavbar: style?.navigationStyle == "custom"
  71. } as PageInstance;
  72. });
  73. }
  74. // 获取指定路径的页面实例
  75. getPage(path: string) {
  76. return this.getPages().find((e) => e.path == path);
  77. }
  78. // 获取当前路由页面实例
  79. route() {
  80. return last(this.getPages());
  81. }
  82. // 获取当前页面路径
  83. path() {
  84. return this.route()?.path ?? "";
  85. }
  86. // 简单跳转页面(默认 navigateTo)
  87. to(path: string) {
  88. this.push({
  89. path
  90. });
  91. }
  92. // 路由跳转,支持多种模式和参数
  93. push(options: PushOptions) {
  94. let {
  95. query = {},
  96. params = {},
  97. mode = "navigateTo",
  98. path,
  99. success,
  100. fail,
  101. complete,
  102. animationType,
  103. animationDuration,
  104. events
  105. } = options;
  106. // 拼接 query 参数到 url
  107. if (!isEmpty(query)) {
  108. const arr = toArray(query, (v, k) => {
  109. return `${k}=${v}`;
  110. });
  111. path += "?" + arr.join("&");
  112. }
  113. // params 通过 storage 临时存储
  114. if (!isEmpty(params)) {
  115. storage.set("router-params", params, 0);
  116. }
  117. // tabBar 页面强制使用 switchTab 跳转
  118. if (this.isTabPage(path)) {
  119. mode = "switchTab";
  120. }
  121. // 跳转执行函数
  122. const next = () => {
  123. switch (mode) {
  124. case "navigateTo":
  125. uni.navigateTo({
  126. url: path,
  127. success,
  128. events,
  129. fail,
  130. complete,
  131. animationType,
  132. animationDuration
  133. });
  134. break;
  135. case "redirectTo":
  136. uni.redirectTo({
  137. url: path,
  138. success,
  139. fail,
  140. complete
  141. });
  142. break;
  143. case "reLaunch":
  144. uni.reLaunch({
  145. url: path,
  146. success,
  147. fail,
  148. complete
  149. });
  150. break;
  151. case "switchTab":
  152. uni.switchTab({
  153. url: path,
  154. success,
  155. fail,
  156. complete
  157. });
  158. break;
  159. }
  160. };
  161. // 跳转前钩子处理
  162. if (isFunction(this._events["beforeEach"])) {
  163. const meta = PAGES.find((e) => e.path == path)?.meta;
  164. const from = this.getPages().slice(-1)[0];
  165. const to: RouteInfo = { path, meta: meta ?? {} };
  166. (this._events["beforeEach"] as BeforeEach)(
  167. to,
  168. from,
  169. next
  170. );
  171. } else {
  172. next();
  173. }
  174. }
  175. // 回到首页
  176. home() {
  177. this.push({
  178. path: this.defaultPath("home")
  179. });
  180. }
  181. // 返回上一页,若为首页则回首页
  182. back(options: BackOptions | null = null) {
  183. let path = ''
  184. const next = ()=>{
  185. if (this.isFirstPage()) {
  186. this.home();
  187. path = this.defaultPath("home")
  188. } else {
  189. path = this.getPages().slice(-2)[0].path;
  190. uni.navigateBack({ ...(options ?? {}) });
  191. }
  192. }
  193. // 跳转前钩子处理
  194. if (isFunction(this._events["beforeEach"])) {
  195. const meta = PAGES.find((e) => e.path == path)?.meta;
  196. const from = this.getPages().slice(-1)[0];
  197. const to: RouteInfo = { path, meta: meta ?? {} };
  198. (this._events["beforeEach"] as BeforeEach)(
  199. to,
  200. from,
  201. next
  202. );
  203. } else {
  204. next();
  205. }
  206. }
  207. // 执行当前页面暴露的方法
  208. callMethod(name: string, data?: any): any | null {
  209. const fn = get(this.route()!, `$vm.$.exposed.${name}`) as (d?: any) => any | null;
  210. if (isFunction(fn)) {
  211. return fn(data);
  212. }
  213. return null;
  214. }
  215. // 判断页面栈是否只有一个页面
  216. isFirstPage() {
  217. return getCurrentPages().length == 1;
  218. }
  219. // 判断是否为首页
  220. isHomePage() {
  221. return this.path() == this.defaultPath("home");
  222. }
  223. // 判断是否为自定义导航栏页面
  224. isCustomNavbarPage() {
  225. return this.route()?.isCustomNavbar ?? false;
  226. }
  227. // 判断是否为当前页面
  228. isCurrentPage(path: string) {
  229. return this.path() == path;
  230. }
  231. // 判断是否为 tab 页面
  232. isTabPage(path: string | null = null) {
  233. if (path == null) {
  234. path = this.path();
  235. }
  236. if (path == "/") {
  237. path = this.defaultPath("home");
  238. }
  239. return !isNull(TABS.find((e) => path == e.pagePath));
  240. }
  241. // 判断是否为登录页
  242. isLoginPage(path: string) {
  243. return path == this.defaultPath("login");
  244. }
  245. // 跳转到登录页(防抖处理)
  246. login = debounce(() => {
  247. if (!this.isLoginPage(this.path())) {
  248. this.push({
  249. path: "/pages/user/login",
  250. mode: "reLaunch"
  251. });
  252. }
  253. }, 300);
  254. // 登录成功后跳转逻辑
  255. nextLogin() {
  256. const pages = this.getPages();
  257. // 找到登录页的索引
  258. const index = pages.findIndex((e) => this.defaultPath("login").includes(e.path));
  259. // 未找到,则跳回首页
  260. if (index < 0) {
  261. this.home();
  262. } else {
  263. this.back({
  264. delta: pages.length - index
  265. });
  266. }
  267. // 登录后回调
  268. if (isFunction(this._events["afterLogin"])) {
  269. (this._events["afterLogin"] as AfterLogin)();
  270. }
  271. // 触发全局 afterLogin 事件
  272. uni.$emit("afterLogin");
  273. }
  274. // 注册跳转前钩子
  275. beforeEach(callback: BeforeEach) {
  276. this._events["beforeEach"] = callback;
  277. }
  278. // 注册登录后回调
  279. afterLogin(callback: AfterLogin) {
  280. this._events["afterLogin"] = callback;
  281. }
  282. }
  283. // 单例导出
  284. export const router = new Router();