|
1 | | -import type { App } from 'vue' |
2 | | -import type { RouterOptions as _RouterOptions, Router } from 'vue-router' |
3 | | -import type { RouterPlugin, RouterPluginContext } from './plugin' |
4 | | -import { effectScope } from 'vue' |
5 | | -import { createRouter as _createRouter } from 'vue-router' |
6 | | -import { APP_KEY } from './meta-keys' |
7 | | - |
8 | | -export interface RouterOptions extends _RouterOptions { |
9 | | - /** |
10 | | - * Plugins to be installed on the router. |
11 | | - */ |
12 | | - plugins?: RouterPlugin[] |
13 | | -} |
14 | | - |
15 | | -/** |
16 | | - * Equivalent to {@link createRouter} from `vue-router`, but with support for plugins. |
17 | | - * @param options {@link RouterOptions} |
18 | | - * |
19 | | - * @example |
20 | | - * ```ts |
21 | | - * createRouter({ |
22 | | - * history: createWebHistory(), |
23 | | - * routes: [], |
24 | | - * plugins: [SomePlugin()], |
25 | | - * }) |
26 | | - * ``` |
27 | | - */ |
28 | | -export function createRouter(options: RouterOptions): Router { |
29 | | - const router = _createRouter(options) |
30 | | - const { plugins = [] } = options |
31 | | - |
32 | | - const effect = effectScope(true) |
33 | | - const runWithAppFns: ((app: App) => void)[] = [] |
34 | | - const uninstallFns: (() => void)[] = [] |
35 | | - |
36 | | - const ctx: RouterPluginContext = { |
37 | | - router, |
38 | | - |
39 | | - runWithApp(fn) { |
40 | | - // 将 fn 包装到 effect 中 |
41 | | - const rawFn = fn |
42 | | - fn = function (this: any, ...args) { |
43 | | - return effect.run(() => rawFn.apply(this, args)) |
44 | | - } |
45 | | - |
46 | | - if (router[APP_KEY]) { |
47 | | - fn(router[APP_KEY]) |
48 | | - } else { |
49 | | - runWithAppFns.push(fn) |
50 | | - } |
51 | | - }, |
52 | | - |
53 | | - onUninstall(fn) { |
54 | | - uninstallFns.push(fn) |
55 | | - }, |
56 | | - } |
57 | | - |
58 | | - // 在 effect 中执行插件 |
59 | | - effect.run(() => { |
60 | | - plugins.forEach((plugin) => plugin(ctx)) |
61 | | - }) |
62 | | - |
63 | | - // 重写 install 方法 |
64 | | - const originalInstall = router.install |
65 | | - router.install = (app: App) => { |
66 | | - originalInstall(app) |
67 | | - |
68 | | - router[APP_KEY] = app |
69 | | - runWithAppFns.forEach((fn) => fn(app)) |
70 | | - runWithAppFns.length = 0 |
71 | | - |
72 | | - // TODO: use https://github.com/vuejs/core/pull/8801 if merged |
73 | | - const { unmount } = app |
74 | | - app.unmount = () => { |
75 | | - effect.stop() |
76 | | - delete router[APP_KEY] |
77 | | - uninstallFns.forEach((fn) => fn()) |
78 | | - uninstallFns.length = 0 |
79 | | - unmount.call(app) |
80 | | - } |
81 | | - } |
82 | | - |
83 | | - return router |
84 | | -} |
| 1 | +export * from './create-router' |
| 2 | +export * from './create-vue-router-plugin' |
| 3 | +export * from './plugin' |
0 commit comments