Vue 3 app.config.globalProperties Property
app.config.globalProperties is a configuration option of the Vue application instance that allows us to add some custom properties or methods globally. These properties or methods can be accessed directly in any component of the application via this .
How to Use globalProperties?
1. Create a Vue Application Instance
First, we need to create a Vue application instance, then use app.config.globalProperties to add global properties or methods.
Example
import
{
createApp
}
from
'vue'
;
import
App from
'./App.vue'
;
const
app
=
createApp
(
App
)
;
2. Add Global Properties or Methods
We can use app.config.globalProperties to add global properties or methods. For example, we add a global method $greet:
Example
app.
config
.
globalProperties
.$greet
=
function
(
name
)
{
console.
log
(
`Hello
,
$
{
name
}
!
`
)
;
}
;
app.
mount
(
'#app'
)
;
3. Use Global Properties or Methods in Components
Once we have added the global method $greet, we can call it directly in any component via this :
Example
Say Hello
When the button is clicked, the console outputs Hello, Vue Developer!.
Use Cases for globalProperties
1. Global Utility Methods
globalProperties is very suitable for defining some global utility methods. For example, we can define a global date-formatting method:
Example
app.
config
.
globalProperties
.$formatDate
=
function
(
date
)
{
return
new
Date
(
date
)
.
toLocaleDateString
(
)
;
}
;
Then this method can be used in any component:
Example
{{ formattedDate }}
2. Global Configuration Parameters
We can also use globalProperties to define some global configuration parameters. For example, we can define a global API URL:
Example
app.
config
.
globalProperties
.$apiUrl
=
'https://api.example.com'
;
Then use this parameter in components:
Example
3. Plugin Extension
When developing Vue plugins,globalProperties is also a very commonly used tool. Through it, plugins can add methods or properties globally, simplifying plugin usage.
For example, we can develop a simple logging plugin:
Example
const
Logger
=
{
install
(
app
)
{
app.
config
.
globalProperties
.$log
=
function
(
message
)
{
console.
log
(
`
[
LOG
]
:
$
{
message
}
`
)
;
}
;
}
}
;
app.
use
(
Logger
)
;
Then use this logging method in components:
Example
Notes
- Naming Conflicts: Because
globalPropertiesis global, you need to be careful when naming to avoid conflicts with methods or properties of other libraries or plugins. - Type Safety: If you are using TypeScript, you may need to add
globalPropertiestype definitions to ensure type safety.
Vue 3 Global API