ibwei / vue3-ts-base

一个基于vue3+typescript+ant-design-vue 搭建的基础代码库,有完善的类型系统,帮助快速搭建 vue3 的基础代码架构。
https://ibwei.github.io/vue3-ts-base/
MIT License
446 stars 128 forks source link

[Help] About Vuex modules with typescript #6

Open xieyezi opened 3 years ago

xieyezi commented 3 years ago

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 commented 3 years ago

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

xieyezi commented 3 years ago

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

xieyezi commented 3 years ago

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

ibwei commented 3 years ago

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

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

xieyezi commented 3 years ago

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

ibwei commented 3 years ago

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

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

xieyezi commented 3 years ago

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

xieyezi commented 3 years ago

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

https://github.com/xieyezi/genji