how to access app.config.globalProperties
withing <script setup lang="ts">
?
I have looked around for several approaches: like this SO post, and tried to combine elements below:
\\ main.ts
import mitt from 'mitt'
const emitter = mitt()
declare module '@vue/runtime-core' {
export interface ComponentCustomProperties {
emitter: typeof mitt
}
}
app.config.globalProperties.emitter = emitter
tried packaging for use in composition-api .. no luck either
\\ bus.ts
import { getCurrentInstance } from 'vue'
const app = getCurrentInstance()
const bus = app.appContext.config.globalProperties.emitter // app is undefined
export const useBus = () => ({ bus })
There are two problems:
setup
or lifecycle hooks of a Vue componentapp.config.globalProperties
are exposed directly on component instancesSo my preferred solution would be:
// bus.ts
import mitt from 'mitt'
export const emitter = mitt()
export const useBus = () => ({ bus: emitter })
// main.ts
import { emitter } from `bus.ts`
declare module '@vue/runtime-core' {
export interface ComponentCustomProperties {
emitter: typeof emitter
}
}
app.config.globalProperties.emitter = emitter
Now you can use this.emitter
in Options API or in templates. And const { bus } = useBus()
in setup
Although I would probably use just single name (either emitter
or bus
) :)