feat(bridge): auto-inject based on provide key from plugins (#3536)

This commit is contained in:
Daniel Roe 2022-03-07 15:08:09 +00:00 committed by GitHub
parent f1d2eb1335
commit 856c01ab42
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 4 deletions

View File

@ -74,8 +74,20 @@ export function callWithNuxt<T extends (...args: any[]) => any> (nuxt: NuxtAppCo
return p return p
} }
export function defineNuxtPlugin (plugin: (nuxtApp: NuxtAppCompat) => void): (ctx: Context) => void { interface Plugin {
return ctx => callWithNuxt(ctx.$_nuxtApp, plugin, [ctx.$_nuxtApp]) (nuxt: NuxtAppCompat): Promise<void> | Promise<{ provide?: Record<string, any> }> | void | { provide?: Record<string, any> }
}
export function defineNuxtPlugin (plugin: Plugin): (ctx: Context, inject: (id: string, value: any) => void) => void {
return async (ctx, inject) => {
const result = await callWithNuxt(ctx.$_nuxtApp, plugin, [ctx.$_nuxtApp])
if (result && result.provide) {
for (const key in result.provide) {
inject(key, result.provide[key])
}
}
return result
}
} }
export const useNuxtApp = (): NuxtAppCompat => { export const useNuxtApp = (): NuxtAppCompat => {

View File

@ -2,10 +2,14 @@ import { onGlobalSetup, ref } from '@nuxtjs/composition-api'
import { defineNuxtPlugin } from '#app' import { defineNuxtPlugin } from '#app'
export default defineNuxtPlugin((nuxtApp) => { export default defineNuxtPlugin(() => {
const globalsetup = ref('🚧') const globalsetup = ref('🚧')
onGlobalSetup(() => { onGlobalSetup(() => {
globalsetup.value = '✅' globalsetup.value = '✅'
}) })
nuxtApp.provide('globalsetup', globalsetup) return {
provide: {
globalsetup
}
}
}) })