'How to write a global store plugin?

I'm trying to make a reactive $store object globally available via plugin but am failing to make it work.

store.ts:

import {reactive} from "vue";

export default {
    install: (app:any, options:any) => {

        app.config.globalProperties.$store = reactive({})
    }
}

main.ts:

import {createApp} from 'vue';
import app from "@/vue/app.vue";
import store from "@/scripts/store";

createApp(app)
    .use(store)
    .mount("#app");

Now I would expect for the plugin to be usable in all components, but $store stays an undeclared variable, when I try to use it in the <script setup> tag inside a component.



Solution 1:[1]

Communication between components in Vue follows a parent-child flow where parents communicate via props and children via events.

It is not a bad idea to centralize the data of the application instead of having it distributed among components, but it is highly inadvisable to have global references.

Instead global reference, creating event buses or a long chain of emits, the classic option in this framework is the Flux pattern. Currently the best implementation of Flux (my opinion) in Vue and the one officially recommended is Pinia. It exactly meets your requirement in a very simple way. It has very good typescript support and you just have to import the stores you need where you need them and they will reactively maintain state throughout the app.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1