vue3-ts-base icon indicating copy to clipboard operation
vue3-ts-base copied to clipboard

[Help] About Vuex modules with typescript

Open xieyezi opened this issue 4 years ago • 8 comments

First of all, this is a amazing project which help me a lot.

But I have some trouble with Vuex in Typescript.

This is my // store/about.ts :

// store/about.ts
import modules from './about'
import { StateType } from '@typing/index'
import { Module } from 'vuex'

type AboutStateType = typeof state

const state = {
	aboutInfo: 'info from about state model'
}
const getters = {}
const mutations = {}
const actions = {}

const about: Module<AboutStateType, StateType> = {
	namespaced: true,
	state,
	getters,
	mutations,
	actions
	modules  // Here,Typescript have warning: 不能将类型“Module<{ aboutInfo: string; }, VuexModuleType>”分配给类型“ModuleTree<VuexModuleType>”。
}
export { AboutStateType, state }
export default about

And my project directory like this:

截屏2021-01-12 16 57 11

In the above example, There are other modules under the about module. But TypeScript Can not Identify the type correctly. I tried to solve this problem, but still don’t know what to do. Can you provide some help for this ? Thanks a lot!

xieyezi avatar Jan 12 '21 09:01 xieyezi

I upload them to github already: https://github.com/xieyezi/vue-vite-template/blob/vuex-modules/src/store/modules/about.ts

xieyezi avatar Jan 12 '21 09:01 xieyezi

modules下面允许有modulds吧Screenshot_2021-01-12-21-19-05-759_com.android.chrome.jpg

xieyezi avatar Jan 12 '21 13:01 xieyezi

https://next.vuex.vuejs.org/guide/modules.html#module-local-state

xieyezi avatar Jan 12 '21 13:01 xieyezi

modules下面允许有modulds吧Screenshot_2021-01-12-21-19-05-759_com.android.chrome.jpg

是的,感谢纠正。因为当初封装的工具函数只考虑到子 module,没有考虑更多层级。我去试了下,在 module 下定义 module 是不会引发 ts 报错的,至于要支持更深层级的 module,我后面再完善一下。另外,考虑到更改读取的便利性,建议扁平化管理数据,而不是嵌套更深。

ibwei avatar Jan 13 '21 06:01 ibwei

@ibwei 对的,官方声称vueX-beta是有这个问题,他们说会在vueX5 版本里面完美解决这个问题,可以查看这个video https://www.youtube.com/watch?v=ajGglyQQD0k&ab_channel=VuejsAmsterdam

xieyezi avatar Jan 13 '21 09:01 xieyezi

@ibwei 对的,官方声称vueX-beta是有这个问题,他们说会在vueX5 版本里面完美解决这个问题,可以查看这个video https://www.youtube.com/watch?v=ajGglyQQD0k&ab_channel=VuejsAmsterdam

image 抱歉,最近一直没空修复这个。你的 ts 报错是因为这个类型的问题吧,state 是const定义的,typeof 取state类型应该在定义之后吧。我最近看了一下,感觉没有找到关于多层次 module 的封装案例,你有好的方法可以分享给我。

ibwei avatar Jan 19 '21 03:01 ibwei

@ibwei 现在没有更好的实现方式,因为子module的类型对于父module来说,是dynamic的,vuex5会解决这个问题。具体可以看上个评论的视频。

xieyezi avatar Jan 19 '21 07:01 xieyezi

我自己写了一个解决方案,完美支持composition API 和 typescript,有兴趣可以看看:

https://github.com/xieyezi/genji

xieyezi avatar May 16 '21 14:05 xieyezi