Skip to content

Commit 958d970

Browse files
committed
feat(client): add support for clientData
1 parent 1fe9635 commit 958d970

File tree

5 files changed

+36
-0
lines changed

5 files changed

+36
-0
lines changed

packages/client/src/app.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { clientConfigs } from '@internal/clientConfigs'
22
import { createApp, createSSRApp, h } from 'vue'
33
import { RouterView } from 'vue-router'
44
import { siteData } from './composables/index.js'
5+
import { clientDataMap } from './helpers/index.js'
56
import { createVueRouter } from './router.js'
67
import { setupGlobalComponents } from './setupGlobalComponents.js'
78
import { setupGlobalComputed } from './setupGlobalComputed.js'
@@ -50,6 +51,11 @@ export const createVueApp: CreateVueAppFunction = async () => {
5051
setupDevtools(app, globalComputed)
5152
}
5253

54+
// provide client data
55+
for (const [key, value] of clientDataMap) {
56+
app.provide(key, value)
57+
}
58+
5359
// invoke all client enhance
5460
for (const clientConfig of clientConfigs) {
5561
await clientConfig.enhance?.({ app, router, siteData })
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { inject } from 'vue'
2+
import type { InjectionKey } from 'vue'
3+
4+
export const useClientData = <T = unknown, U extends boolean = false>(
5+
key: InjectionKey<T>,
6+
required?: U
7+
): U extends true ? T : T | undefined => {
8+
const result = inject(key)
9+
10+
if (required && !result) {
11+
throw new Error(`Can not found ${key} in clientData()`)
12+
}
13+
14+
return <U extends true ? T : T | undefined>result
15+
}

packages/client/src/composables/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
export * from './clientData.js'
12
export * from './layouts.js'
23
export * from './pageData.js'
34
export * from './pageFrontmatter.js'
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import type { InjectionKey } from 'vue'
2+
3+
export const clientDataMap = new Map<InjectionKey<unknown>, unknown>()
4+
5+
/**
6+
* A helper function to help you define vuepress client data
7+
*/
8+
export const defineClientData = <T = unknown>(
9+
key: InjectionKey<T>,
10+
data: T
11+
): void => {
12+
clientDataMap.set(key, data)
13+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
export * from './defineClientConfig.js'
2+
export * from './defineClientData.js'
23
export * from './withBase.js'

0 commit comments

Comments
 (0)