|
| 1 | +import type { App } from 'vue' |
| 2 | +import type { Router } from 'vue-router' |
| 3 | +import type { RouterPlugin } from './plugin' |
| 4 | +import { overrideRouterInstall } from './override-router-install' |
| 5 | +import { prepareInstall } from './prepare-install' |
| 6 | +import { setupPlugin } from './setup-plugin' |
| 7 | + |
| 8 | +export interface RouterPluginInstall { |
| 9 | + /** |
| 10 | + * Install the plugin. |
| 11 | + * @param instance App or Router instance |
| 12 | + */ |
| 13 | + install: (instance: App | Router) => void |
| 14 | +} |
| 15 | + |
| 16 | +/** |
| 17 | + * Add an `install` method to the plugin to adapt it to Vue's plugin registration mechanism, |
| 18 | + * or to manually install the plugin with an router instance. |
| 19 | + * |
| 20 | + * @example |
| 21 | + * ```ts |
| 22 | + * const SomePlugin = withInstall((ctx) => { |
| 23 | + * // plugin implementation |
| 24 | + * }) |
| 25 | + * |
| 26 | + * // install with router |
| 27 | + * SomePlugin.install(router) |
| 28 | + * |
| 29 | + * // install with app |
| 30 | + * // must be installed after the router |
| 31 | + * app.use(router).use(SomePlugin) |
| 32 | + * ``` |
| 33 | + */ |
| 34 | +export function withInstall( |
| 35 | + plugin: RouterPlugin, |
| 36 | +): RouterPlugin & RouterPluginInstall { |
| 37 | + return Object.assign(plugin, { |
| 38 | + install(instance: App | Router) { |
| 39 | + if (isRouter(instance)) { |
| 40 | + overrideRouterInstall(instance) |
| 41 | + setupPlugin({ router: instance, plugin }) |
| 42 | + } |
| 43 | + else { |
| 44 | + const router = instance.config.globalProperties.$router |
| 45 | + if (!router) { |
| 46 | + throw new Error( |
| 47 | + '[vue-router-plugin-system] Please install vue-router first.', |
| 48 | + ) |
| 49 | + } |
| 50 | + |
| 51 | + prepareInstall({ app: instance, router }) |
| 52 | + setupPlugin({ router, plugin }) |
| 53 | + } |
| 54 | + }, |
| 55 | + }) |
| 56 | +} |
| 57 | + |
| 58 | +function isRouter(instance: any): instance is Router { |
| 59 | + return !!instance.install && !!instance.options && !!instance.currentRoute |
| 60 | +} |
0 commit comments