I'm trying to set up a Vue3 app with a Vuex4 store but I can't seem to get the store accessible in any component, always some undefined error. I've tried many other solutions but seem to keep running in circles when I go to finally test so I feel like this is something simple I'm missing.
main.ts:
import App from "./App.vue";
import { createApp } from "vue";
import createRouter from "@/router"
import createStore from "@/store"
const app = createApp(App);
const store = createStore();
const router = createRouter(app, store);
app
.use(store)
.use(router);
router.isReady().then(() => {
app.mount('#app');
});
router/index.ts:
import { createRouter, createWebHistory } from "vue-router"
import AppLayout from '../layouts/AppLayout.vue'
import { App } from 'vue';
export default function (app: App, store: any) {
const routes = [
{
path: "/",
component: AppLayout,
children: [
{
path: '',
component: () => import('../views/Dashboard.vue'),
},
{
path: 'accounts',
component: () => import('../views/Accounts.vue'),
},
]
},
]
const router = createRouter({
routes,
history: createWebHistory()
})
return router
}
store/index.ts:
import { createStore } from "vuex"
const store = {
state: () => ({
foo: "bar",
})
}
export default function () {
return createStore(store)
}
views/Dashboard.vue
<script>
// ??? all some variation of undefined
// console.log(this.$store)
// console.log(this.store)
// console.log(store)
// import { useStore } from "vuex";
// const store = useStore();
// console.log(store)
</script>
Have you tried to debug like this?
<script>
export default {
mounted() {
console.log(this.$store);
},
};
</script>
Your setup seems ok, but then at components you should be able to get store from inside export default
at Options API. If using Composition then you need to do this
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
}
}