0
0
Vueframework~5 mins

Global properties and methods in Vue

Choose your learning style9 modes available
Introduction

Global properties and methods let you share values or functions across all Vue components easily. This helps avoid repeating code and keeps your app organized.

You want to use the same helper function in many components without importing it each time.
You need to share a global configuration value, like an API base URL, across your app.
You want to add a global method for formatting dates or numbers used everywhere.
You want to add a global property for theme colors or user settings accessible in all components.
Syntax
Vue
import { createApp } from 'vue'
const app = createApp(App)

app.config.globalProperties.$myMethod = () => {
  // your code here
}

app.mount('#app')
Global properties are added to app.config.globalProperties and accessed in components with this.$myMethod.
Use a $ prefix to avoid name conflicts with component data or methods.
Examples
This adds a global method $formatDate to format dates in all components.
Vue
app.config.globalProperties.$formatDate = (date) => {
  return new Date(date).toLocaleDateString()
}
This adds a global property $appName that holds the app name string.
Vue
app.config.globalProperties.$appName = 'My Vue App'
This adds a global method $log to print messages with a prefix.
Vue
app.config.globalProperties.$log = (msg) => console.log('Log:', msg)
Sample Program

This example shows how to add global properties and methods to a Vue app. The app displays the app name and formatted date using global properties. The button uses a global method to log a message when clicked.

Vue
import { createApp } from 'vue'

const App = {
  template: `<div>
    <h1>{{ $appName }}</h1>
    <p>Today is: {{ $formatDate(new Date()) }}</p>
    <button @click="$log('Button clicked!')">Click me</button>
  </div>`
}

const app = createApp(App)

app.config.globalProperties.$appName = 'My Vue App'
app.config.globalProperties.$formatDate = (date) => {
  return new Date(date).toLocaleDateString()
}
app.config.globalProperties.$log = (msg) => console.log('Log:', msg)

app.mount('#app')
OutputSuccess
Important Notes

Global properties are accessible inside component templates and methods via this.$propertyName.

Use global properties sparingly to avoid making components too dependent on global state.

For better type safety and IDE support, consider using provide/inject or composables for shared logic in larger apps.

Summary

Global properties and methods let you share code across all Vue components easily.

Add them using app.config.globalProperties with a $ prefix.

Use them in templates and scripts with this.$propertyName.