在 Vue.js 3 中添加全局变量 [英] Add global variable in Vue.js 3
问题描述
有人知道如何在 Vue 3 中添加全局变量吗?
Anybody know how to do add a global variable in Vue 3 ?
在 Vue 2 中,我们在 main.js
文件中使用它:
in Vue 2 we use this in the main.js
file:
Vue.prototype.$myGlobalVariable = globalVariable
推荐答案
最直接的替代方案是 app.config.globalProperties
.见:
The most direct replacement is app.config.globalProperties
. See:
https://v3.vuejs.org/api/application-config.html#globalproperties
所以:
Vue.prototype.$myGlobalVariable = globalVariable
变成:
const app = Vue.createApp({})
app.config.globalProperties.$myGlobalVariable = globalVariable
请注意,这仅限于特定应用程序,而不是像 Vue.prototype
那样是全局的.这是设计使然,所有全局配置选项现在都适用于应用程序.
Note that this is scoped to a particular application rather than being global as it was with Vue.prototype
. This is by design, all global configuration options are now scoped to an application.
相关的 RFC 在这里:
The relevant RFC is here:
https://github.com/vuejs/rfcs/blob/master/active-rfcs/0009-global-api-change.md
请注意,应用程序级 provide
/inject
(也在该 RFC 中讨论)也是使用 Vue.prototype
的替代方法:
Note that application-level provide
/inject
(also discussed in that RFC) is also an alternative to using Vue.prototype
:
const app = Vue.createApp({})
app.provide('myGlobalVariable', globalVariable)
// In the descendant component
export default {
inject: ['myGlobalVariable']
}
文档:https://v3.vuejs.org/api/application-api.html#provide
这里的想法是组件可以显式声明属性而不是通过魔法继承它.这避免了名称冲突等问题,因此无需使用 $
前缀.它还有助于更清楚地说明财产的确切来源.
The idea here is that the component can explicitly declare the property rather than inheriting it by magic. That avoids problems like name collisions, so there's no need to use a $
prefix. It can also help to make it clearer where exactly a property is coming from.
您喜欢哪种方法取决于您的情况.
Which approach you prefer will depend on your circumstances.
这篇关于在 Vue.js 3 中添加全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!