Add global variable in Vue.js 3

Adri HM picture Adri HM · Jul 26, 2020 · Viewed 10.6k times · Source

Anybody know how to do add a global variable in Vue 3 ?

in Vue 2 we use this in the main.js file:

Vue.prototype.$myGlobalVariable = globalVariable

Answer

skirtle picture skirtle · Jul 26, 2020

The most direct replacement is app.config.globalProperties. See:

https://v3.vuejs.org/api/application-config.html#globalproperties

So:

Vue.prototype.$myGlobalVariable = globalVariable

becomes:

const app = Vue.createApp({})
app.config.globalProperties.$myGlobalVariable = globalVariable

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.

The relevant RFC is here:

https://github.com/vuejs/rfcs/blob/master/active-rfcs/0009-global-api-change.md

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']
}

Docs: 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.