Vue3 app.config.globalProperties Property
app.config.globalPropertiesis a configuration item of the Vue application instance that allows us to add some custom properties or methods globally. These properties or methods can be directly accessed in any component of the application throughthisaccess.
How to use globalProperties?
1. Create a Vue application instance
First, we need to create a Vue application instance, and then throughapp.config.globalPropertiesto add global properties or methods.
Example
import App from './App.vue';
const app = createApp(App);
2. Add global properties or methods
We can useapp.config.globalPropertiesto add global properties or methods. For example, we add a global method$greet:
Example
console.log(`Hello, ${name}!`);
};
app.mount('#app');
3. Use global properties or methods in components
Once we have added a global method$greet, we can in any component throughthisdirectly call it:
Example
<button @click="sayHello">Say Hello</button>
</template>
<script>
export default {
methods: {
sayHello() {
this.$greet('Vue Developer');
}
}
}
</script>
When the button is clicked, the console will outputHello, Vue Developer!。
Application scenarios of globalProperties
1. Global utility methods
globalPropertiesIt is very suitable for defining some global utility methods. For example, we can define a global date formatting method:
Example
return new Date(date).toLocaleDateString();
};
Then this method can be used in any component:
Example
<div>{{ formattedDate }}</div>
</template>
<script>
export default {
data() {
return {
date: '2025-03-10'
};
},
computed: {
formattedDate() {
return this.$formatDate(this.date);
}
}
}
</script>
2. Global configuration parameters
We can also useglobalPropertiesto define some global configuration parameters. For example, we can define a global API URL:
Example
Then use this parameter in components:
Example
export default {
created() {
console.log('API URL:', this.$apiUrl);
}
}
</script>
3. Plugin extension
When developing Vue plugins,globalPropertiesis also a very commonly used tool. Through it, plugins can add some methods or properties globally, thereby simplifying the use of the plugin.
For example, we can develop a simple logging plugin:
Example
install(app) {
app.config.globalProperties.$log = function(message) {
console.log(`[LOG]: ${message}`);
};
}
};
app.use(Logger);
Then use this logging method in components:
Example
export default {
mounted() {
this.$log('Component is mounted!');
}
}
</script>
Precautions
- Naming conflict: Since
globalPropertiesis global, so 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
globalPropertiesadd type definitions to ensure type safety.
Other extensions
Vue3 Global API