Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Vue 3 app.config.globalProperties Property

Vue 3 app.config.globalProperties Property


Vue3 Global API Vue 3 Global API

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

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

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

  1. Naming Conflicts: Because globalProperties is global, you need to be careful when naming to avoid conflicts with methods or properties of other libraries or plugins.
  2. Type Safety: If you are using TypeScript, you may need to add globalProperties type definitions to ensure type safety.

Vue3 Global API Vue 3 Global API