javascript - Vue3在js文件中使用全局变量

标签 javascript vue.js global-variables vuejs3 vue-composition-api

我在 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/

相关文章:

laravel - Vuejs Axios POST 请求从 Laravel 后端获取 HTTP422 错误

javascript - Vue.js eslint 解析错误。 : unexpected token

ruby - 使用 $& 全局变量的编程别名方法

c - Xcode中编译时全局变量错误(C编程)

javascript - 使用Lambda在DynamoDB上批量写入超过25个项目

javascript - 在Windows中的meteor中编辑文件重新启动服务器

javascript - `$(document).on("方法1",function(event,param)`与通常的函数method1(){}相同吗?

javascript - 在 react.js 中扩展样式对象

vue.js - 在 Vuex Store 中正确使用 setInterval

python - 在 Python unittest 框架中修改全局变量