Categories
Vue Answers

How to add global variables in Vue.js 3?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *