我在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中导入并执行可组合的组件:
import { useGlobals } from '../path'
const { global } = useGlobals('locale')现在,可以使用全局变量。
但是,当我在js文件中导入可组合时,appContext是未定义的,就会出现问题。
我的问题是,有什么方法可以在appContext文件中获得全局变量或js?
发布于 2022-10-01 14:42:31
感谢@陶(顺便说一句)的伟大建议,不可能从应用程序获得appContext,但这给了我一个想法:)问题得到了解决。
在应用程序创建之后,我在main.js中创建了另一个具有所有全局属性的导出:
const globals = app.config.globalProperties
export { globals }或作为一种功能(另一种@陶建议):
export const useGlobals = () => app.config.globalProperties现在,我们可以在任何js文件中导入全局文件,并将其使用如下:
import { globals } from '../path'
globals.$locale或从职能:
import { useGlobals } from '../path'
const { $locale } = useGlobals()发布于 2022-10-01 13:27:24
您可以使用provide/inject机制,而不是创建可组合的全局道具。
查看这里的文档:https://vuejs.org/api/composition-api-dependency-injection.html#provide
https://stackoverflow.com/questions/73917711
复制相似问题