Search code examples
javascriptvue.jsglobal-variablesvuejs3vue-composition-api

Vue3 use global variable in js files


I have some global variables in Vue3 project defined like:

 app.config.globalproperties.$locale = locale

then composable is created to dynamically return global variable:

import { getCurrentInstance ) from 'vue'
export function useGlobals(type) {
  const app = getCurrentInstance()
  const global = app.appContext.config.globalProperties[`$${type}`]
  return { global }
}

then in vue components composable is imported and executed:

import { useGlobals } from '../path'
const { global } = useGlobals('locale')

now, global variable can be used.

But the problem arise when I import composable in js files, there the appContext is undefined.

My question is, is there a way we can get global variable or appContext in js files?


Solution

  • Thanks to great suggestion from @tao (btw it is impossible to get appContext from app but that gives me an idea :)) issue is solved.

    I created another export in main.js, after app creation, with the all global properties:

    const globals = app.config.globalProperties
    export { globals }
    

    or as a function (another @tao suggestion):

    export const useGlobals = () => app.config.globalProperties
    

    Now we can import globals in any js file and use it like:

    import { globals } from '../path/to/main.js'
    globals.$locale
    

    or from function :

    import { useGlobals } from '../path/to/main.js'
    const { $locale } = useGlobals()