How to add global variables in Vue.js 3?

Sometimes, we want to add global variables in Vue.js 3.

In this article, we’ll look at how to add global variables in Vue.js 3.

How to add global variables in Vue.js 3?

To add global variables in Vue.js 3, we add properties to the app.config.globalProperties object.

For instance, we write

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

to create a Vue app with Vue.createApp.

Then we add the $myGlobalVariable variable and set it to globalVariable with

app.config.globalProperties.$myGlobalVariable = globalVariable

Then in our components, we can access the global variable with

this.$myGlobalVariable

Conclusion

To add global variables in Vue.js 3, we add properties to the app.config.globalProperties object.