Vue3 use global variable in js files

Nikola Pavicevic

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?

Nikola Pavicevic

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 useAppConfig = () => app.config

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

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

or from function :

import { useAppConfig } from '../path'
const { globalProperties } = useAppConfig()
globalProperties.$locale

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related