In Vue 3, the best way to define global variables is by adding them to app.config.globalProperties during app setup. This makes them accessible across the entire app.
Vue 3: Use app.config.globalProperties
The cleanest way to declare global variables in Vue 3 is by adding them to app.config.globalProperties.
// main.jsimport { createApp } from ‘vue’import App from ‘./App.vue’
const app = createApp(App)
app.config.globalProperties.$appName = ‘My App’
app.mount(‘#app’)
Usage in a component;
export default { mounted() {
console.log(this.$appName)
}
}
Other Options
While globalProperties is the most common way, here are three others:
1. Provide/Inject (For Scoped Globals)
Useful when passing global-like values down a component tree without prop drilling.
main.js
const app = createApp(App)app.provide(‘apiBase’, ‘https://api.example.com’)
app.mount(‘#app’)
Component.vue
import { inject } from ‘vue’
export default {
setup() {
const apiBase = inject(‘apiBase’)
console.log(apiBase)
}
}
2. Pinia (For Reactive Global State)
Ideal for shared reactive state across components.
store.js
import { defineStore } from ‘pinia’
export const useAppStore = defineStore(‘app’, {
state: () => ({
userName: ‘Guest’
})
})
Component.vue
import { useAppStore } from ‘./store’
export default {
setup() {
const store = useAppStore()
console.log(store.userName) // reactive
}
}
Also Read: Best Vue Component Libraries to Build Stunning Frontends
3. Environment Variables (For Static Globals)
Use .env files to define static config values:
.env
Component.vue
Key Takeaway
- Use app.config.globalProperties in Vue 3 to define global variables.
- Use provide/inject or env vars for scoped or config driven values.