wangrong
5 小时以前 a611c225b17219e873b60888e03c330fbe0c57a4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
import { last } from "lodash-es";
import { ctx } from "virtual:ctx";
import { storage } from "../utils";
import { config } from "../../config";
 
type PushOptions =
    | string
    | {
            path: string;
            mode?: "navigateTo" | "redirectTo" | "reLaunch" | "switchTab" | "preloadPage";
            events?: {
                [key: string]: (data: any) => void;
            };
            query?: {
                [key: string]: any;
            };
            params?: {
                [key: string]: any;
            };
            isGuard?: boolean;
            [key: string]: any;
      };
 
type Tabs = {
    text?: string;
    pagePath: string;
    iconPath?: string;
    selectedIconPath?: string;
    [key: string]: any;
}[];
 
// 路由列表
const routes = [...ctx.pages];
 
// 子包
if (ctx.subPackages) {
    ctx.subPackages.forEach((a: { pages: any[]; root: string }) => {
        a.pages.forEach((b) => {
            routes.push({
                ...b,
                path: a.root + "/" + b.path,
            });
        });
    });
}
 
// 钩子函数
const fn: { [key: string]: (...args: any[]) => any } = {};
 
// 路由
const router = {
    // 底部导航
    get tabs(): Tabs {
        if (ctx.tabBar) {
            return ctx.tabBar.list || [];
        } else {
            return [];
        }
    },
 
    // 全局样式配置
    globalStyle: ctx.globalStyle,
 
    // 路由列表
    routes,
 
    // 跳转参数(地址栏)
    get query() {
        const info = this.info();
 
        return {
            ...info?.query,
        };
    },
 
    // 跳转参数(缓存)
    get params() {
        return storage.get("router-params") || {};
    },
 
    // 页面路径
    get pages() {
        return {
            home: "/" + (ctx.tabBar ? this.tabs[0].pagePath : ctx.pages[0].path),
            ...config.app.pages,
        };
    },
 
    // 当前页面信息
    currentPage(): { [key: string]: any } {
        return last(getCurrentPages())!;
    },
 
    // 当前路由路径
    get path() {
        return router.info()?.path;
    },
 
    // 当前路由信息
    info() {
        const page = last(getCurrentPages());
 
        if (page) {
            const { route, $page, $vm, $getAppWebview }: any = page;
 
            const q: any = {};
 
            try {
                $page?.fullPath
                    .split("?")[1]
                    .split("&")
                    .forEach((e: string) => {
                        const [k, v] = e.split("=");
                        q[k] = decodeURIComponent(v);
                    });
            } catch (e) {}
 
            // 页面配置
            const style = this.routes.find((e) => e.path == route)?.style;
 
            let d = {
                $vm,
                $getAppWebview,
                path: `/${route}`,
                fullPath: $page?.fullPath,
                query: q || {},
                isTab: this.isTab(route),
                style,
                isCustomNavbar: style?.navigationStyle == "custom",
            };
 
            return d;
        } else {
            return null;
        }
    },
 
    // 路由跳转
    push(options: PushOptions) {
        if (typeof options == "string") {
            options = {
                path: options,
                mode: "navigateTo",
            };
        }
 
        let {
            path,
            mode = "navigateTo",
            animationType,
            animationDuration,
            events,
            success,
            fail,
            complete,
            query,
            params,
            isGuard = true,
        } = options || {};
 
        if (query) {
            let arr = [];
 
            for (let i in query) {
                if (query[i] !== undefined) {
                    arr.push(`${i}=${query[i]}`);
                }
            }
 
            path += "?" + arr.join("&");
        }
 
        if (params) {
            storage.set("router-params", params);
        }
 
        let data = {
            url: path,
            animationType,
            animationDuration,
            events,
            success,
            fail,
            complete,
        };
 
        if (this.isTab(path)) {
            mode = "switchTab";
        }
 
        const next = () => {
            switch (mode) {
                case "navigateTo":
                    uni.navigateTo(data);
                    break;
 
                case "redirectTo":
                    uni.redirectTo(data);
                    break;
 
                case "reLaunch":
                    uni.reLaunch(data);
                    break;
 
                case "switchTab":
                    uni.switchTab(data);
                    break;
 
                case "preloadPage":
                    uni.preloadPage(data);
                    break;
            }
        };
 
        if (fn.beforeEach && isGuard) {
            fn.beforeEach({ path: options.path, query }, next, (options: PushOptions) => {
                this.push(options);
            });
        } else {
            next();
        }
    },
 
    // 后退
    back(options?: UniApp.NavigateBackOptions) {
        if (this.isFirstPage()) {
            this.home();
        } else {
            uni.navigateBack(options || {});
        }
    },
 
    // 执行当前页面的某个方法
    callMethod(name: string, data?: any) {
        const { $vm } = this.info()!;
 
        if ($vm) {
            if ($vm.$.exposed?.[name]) {
                return $vm.$.exposed[name](data);
            }
        }
    },
 
    // 页面栈长度是否只有1
    isFirstPage() {
        return getCurrentPages().length == 1;
    },
 
    // 是否当前页
    isCurrentPage(path: string) {
        return this.info()?.path == path;
    },
 
    // 回到首页
    home() {
        this.push(this.pages.home);
    },
 
    // 跳转 Tab 页
    switchTab(name: string) {
        let item = this.tabs.find((e) => e.pagePath.includes(name));
 
        if (item) {
            this.push({
                path: `/${item.pagePath}`,
                mode: "switchTab",
            });
        } else {
            console.error("Not found tab", name);
        }
    },
 
    // 是否是 Tab 页
    isTab(path: string) {
        return !!this.tabs.find((e) => path == `/${e.pagePath}`);
    },
 
    // 去登陆
    login(options?: { reLaunch: boolean }) {
        const { reLaunch = false } = options || {};
 
        this.push({
            path: this.pages.login,
            mode: reLaunch ? "reLaunch" : "navigateTo",
            isGuard: false,
        });
    },
 
    // 登录成功后操作
    nextLogin(type?: string) {
        const pages = getCurrentPages();
        const index = pages.findIndex((e) => this.pages.login.includes(e.route!));
 
        if (index <= 0) {
            this.home();
        } else {
            router.back({
                delta: pages.length - index,
            });
        }
 
        // 登录方式
        storage.set("loginType", type);
 
        // 登录回调
        if (fn.afterLogin) {
            fn.afterLogin();
        }
 
        // 事件
        uni.$emit("afterLogin", { type });
    },
 
    // 跳转前钩子
    beforeEach(callback: (to: any, next: () => void) => void) {
        fn.beforeEach = callback;
    },
 
    // 登录后回调
    afterLogin(callback: () => void) {
        fn.afterLogin = callback;
    },
};
 
export { router };