我在 Vue3 项目中定义了一些全局变量,如下所示:
app.config.globalproperties.$locale = locale
然后创建可组合以动态返回全局变量:
import { getCurrentInstance ) from 'vue'
export function useGlobals(type) {
const app = getCurrentInstance()
const global = app.appContext.config.globalProperties[`$${type}`]
return { global }
}
然后在 vue components composable 中导入并执行:
import { useGlobals } from '../path'
const { global } = useGlobals('locale')
现在可以使用全局变量了。
但是当我在 js
文件中导入 composable 时,问题出现了,那里的 appContext
是未定义的。
我的问题是,有没有办法在 js
文件中获取全局变量或 appContext
?
最佳答案
感谢@tao 的好建议(顺便说一句,不可能从应用程序获取 appContext,但这给了我一个想法 :))问题已解决。
在创建应用后,我在 main.js
中创建了另一个导出,具有所有全局属性:
const globals = app.config.globalProperties
export { globals }
或者作为一个函数(另一个@tao的建议):
export const useGlobals = () => app.config.globalProperties
现在我们可以在任何 js
文件中导入全局变量并像这样使用它:
import { globals } from '../path'
globals.$locale
或来自函数:
import { useGlobals } from '../path'
const { $locale } = useGlobals()
关于javascript - Vue3在js文件中使用全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73917711/