Search code examples
vuejs3vue-composition-apievent-busvue-script-setup

How to access `app.config.globalProperties` in a`<script setup lang="ts">`?


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 })


Solution

  • There are two problems:

    1. You can use getCurrentInstance only in setup or lifecycle hooks of a Vue component
    2. Properties added to app.config.globalProperties are exposed directly on component instances

    So 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) :)