Currently, I am working on a Vue3 project with SSR, Vue-Cli, Vuex, and Typescript.
While trying to commit data to the Vuex Store from the router page, I faced an issue. In a .vue file, it's straightforward as I can use this.$store with the typings in vuex.d.ts like this:
this.$store.commit("setFoo", "Bar")
However, when attempting to do the same from a ts file (router/index.ts) where there is no 'this' or vue instance, I encountered difficulties.
I attempted importing the store index file and committing:
import store from "@/store/index"
store.commit("setFoo", "Bar")
This led to an error:
Property 'commit' does not exist on type '() => Store<{ foo: string; }>'.ts(2339)
My store file (as SSR prevents singleton stores) looks like this:
import Vuex from "vuex"
export default function () {
return new Vuex.Store({
state: () => ({
foo: "foo",
}),
mutations: {
setFoo(state, payload) {
state.foo = payload
},
},
})
}
For Vuex 4, the updated store file is:
import { createStore } from "vuex"
const store = {
state: () => ({
foo: "foo",
})
}
export default function () {
return createStore(store)
}
In entry-client.js:
import createApp from "./main"
const { app, router } = createApp()
router.isReady().then(() => {
app.mount("#app", true)
})
As for entry-server.ts:
import createApp from "./main"
export default function () {
const { app, router } = createApp()
return {
app,
router,
}
}
In main.js:
import { createSSRApp, createApp, h } from "vue"
// other imports...
export default function () {
// implementation details...
return {
app,
router,
store,
}
}
Within Router/index.ts:
import { createRouter, createWebHistory, createMemoryHistory } from "vue-router"
// other imports...
export default function () {
return router
}
The package.json includes various scripts, dependencies, and devDependencies related to the project setup.