I am trying to create a global store using only the Vue 3 Composition API.
Until now I have been doing experimentation, and I read a lot how to use the Composition API, but right know I don't know how to use the provide
and the inject
.
All I know is that the provide
will have all the data that will pass to a child component, so I thought that I should import the store into the main.ts
. And the code looks like this:
This is the store (src/store/index.ts):
import { reactive, readonly } from "vue";
const state = reactive({
fnacResults: [],
interResults: [],
});
export default { state: readonly(state) };
This is the main.ts
:
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store/index";
createApp({ provide: { store }, }, App)
.use(router)
.mount("#app");
And when the parent component has the data, if I use the inject
, I will be able to have access to all the data inside of the store. But in my case, it doesn't work. I have a feeling that the error starts when I set the provide
in my main.ts
file.
Have you tried to create a global store using the Composition API with provide
and inject
?
Btw, my component file (src/views/Home.vue
) looks like this:
<template>
<div>{{ store.state.fnacResults }}</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
inject: ['store']
});
</script>