Javascript is required
Mokkapps Logo

Vue Tip: Use Vue App Instance as Global Store

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
Jul 25, 2022
1 min read
|
195 views
Template
Script
Use Vue App Instance as Global Store Image

Vue provides globalProperties on the app instance, an object that can be used to register global properties that can be accessed on any component instance inside the application.

Info

This is a replacement of Vue 2's Vue.prototype which is no longer present in Vue 3.

main.js
import { createApp } from 'vue'const app = createApp({  /* root component options */})app.config.globalProperties.msg = 'hello'

msg can be accessed on any component instance inside the application:

MyComponent.vue
<script>export default {  mounted() {    console.log(this.msg) // 'hello'  },}</script>
Warning

As with anything global, this should be used sparingly. If your app state is too complex, it's better to use Pinia.


If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more content from me. Alternatively (or additionally), you can also subscribe to my newsletter.