Skip to content

Commit 7e3ae90

Browse files
committed
feat(install): 新增 batchInstall 函数用于批量安装插件
1 parent 05db1e6 commit 7e3ae90

File tree

4 files changed

+32
-1
lines changed

4 files changed

+32
-1
lines changed

src/batch-install.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import type { Router } from 'vue-router'
2+
import type { RouterPlugin } from './plugin'
3+
import { withInstall } from './with-install'
4+
5+
/**
6+
* Install multiple plugins to a router instance at once.
7+
* This is equivalent to calling `plugin.install(router)` for each plugin.
8+
* @param router router instance
9+
* @param plugins plugins to install
10+
*
11+
* @example
12+
* ```ts
13+
* batchInstall(router, [AuthPlugin, CachePlugin])
14+
* ```
15+
*/
16+
export function batchInstall(router: Router, plugins: RouterPlugin[]): void {
17+
plugins.forEach(plugin => withInstall(plugin).install(router))
18+
}

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
export * from './batch-install'
12
export * from './create-router'
23
export * from './deprecated/as-vue-plugin'
34
export * from './deprecated/create-vue-router-plugin'

src/override-router-install.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ export function overrideRouterInstall(router: Router): void {
1313
return
1414
}
1515

16-
// 避免重复重写
16+
// 避免多次重写
1717
internals.isInstallOverridden = true
1818

1919
// 重写 install 方法

src/with-install.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@ export interface RouterPluginInstall {
1313
install: (instance: App | Router) => void
1414
}
1515

16+
const WITH_INSTALL = '__WITH_INSTALL__'
17+
18+
type RouterPluginInternal = RouterPlugin & {
19+
[WITH_INSTALL]?: true
20+
}
21+
1622
/**
1723
* Add an `install` method to the plugin to adapt it to Vue's plugin registration mechanism,
1824
* or to manually install the plugin with an router instance.
@@ -34,7 +40,13 @@ export interface RouterPluginInstall {
3440
export function withInstall(
3541
plugin: RouterPlugin,
3642
): RouterPlugin & RouterPluginInstall {
43+
if ((plugin as RouterPluginInternal)[WITH_INSTALL]) {
44+
return plugin as RouterPlugin & RouterPluginInstall
45+
}
46+
3747
return Object.assign(plugin, {
48+
[WITH_INSTALL]: true,
49+
3850
install(instance: App | Router) {
3951
if (isRouter(instance)) {
4052
overrideRouterInstall(instance)

0 commit comments

Comments
 (0)