Home > Mobile >  Vue3 use global variable in js file
Vue3 use global variable in js file

Time:10-02

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?

CodePudding user response:

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 }

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

import { globals } from '../path'
globals.$locale

Please look below, in comments, to get even better solution with exporting as a function.

CodePudding user response:

instead of creating your composable to get global props, you can use the provide/inject mechanism.

check the documentation here: https://vuejs.org/api/composition-api-dependency-injection.html#provide

  • Related