如何解决Vuex 模块装饰器:如何访问模块内的存储
我一直在尝试使用 vuex 模块装饰器来在我的 vuex 商店中保持良好的打字稿。但是我在尝试访问商店而不遇到类型定义问题时遇到了困难。
我正在使用:
- 带有“nuxt-typescript”和“vue2-composition-api”的nuxt,
- 带有“vuex-module-decorator”设置的 vuex 和用于 SSR 的 getModule,
这是我尝试的基本示例:
store/index.ts
import { Store } from 'vuex'
import { getModule } from 'vuex-module-decorators'
import User from './user'
import Basket from './basket'
export function useUserModule(store: Store<any>): UserModule {
return getModule(UserModule,store)
}
export function useBasketModule(store: Store<any>): BasketModule {
return getModule(BasketModule,store)
}
store/user.ts
import { Module,VuexModule,Action } from 'vuex-module-decorators'
@Module({
name: 'user',namespaced: true,stateFactory: true,preserveState: true,})
export default class UserModule extends VuexModule {
user: IUser | null = null
@Action
async doSomthingWithUser(request: object) {
console.log('success!,called from basket module')
}
}
store/basket.ts
import { Module,Action } from 'vuex-module-decorators'
import { useUserModule } from '.'
@Module({
name: 'basket',})
export default class BasketModule extends VuexModule {
basket: IBasket | null = null
@Action
async doUserAction(request: object) {
const userStore = useUserModule(this.store)
//Property 'store' does not exist on type 'BasketModule'
userStore.doSomthingWithUser({stuff:true})
}
}
Property 'store' does not exist on type 'BasketModule'
当我控制台日志 this.store
时,问题是 this
确实存在!
我发现的示例 here 使用了对我来说不存在的 this.$store
。
例如:getModule(MobuleB,this.$store)
我也尝试过使用文档 decorators with ServerSideRender 中描述的传统方法来处理 nuxt SSR...但情况完全相同。
一切正常……但 IDE 出现错误,我是打字稿的新手,我认为该模块没有存储的类型定义。任何人都知道我如何为所有模块分配 this.store
的定义,或者使用其他人都可以访问的全局 this.$store
吗?
解决方法
这并不理想,但您可以将 .d.ts 复制到您自己的 shim 文件中,并将商店引用添加到类中。在项目的根目录添加一个名为“shims-vuex-module-decorator.ts”的文件,内容如下
import {
ActionTree,GetterTree,Module as Mod,ModuleTree,MutationTree,Store,ActionContext,} from 'vuex'
declare module 'vuex-module-decorators' {
export class VuexModule<S = ThisType<any>,R = any> implements Mod<S,R> {
static namespaced?: boolean
static state?: any | (() => any)
static getters?: GetterTree<any,any>
static actions?: ActionTree<any,any>
static mutations?: MutationTree<any>
static modules?: ModuleTree<any>
modules?: ModuleTree<any>
namespaced?: boolean
getters?: GetterTree<S,R>
state?: S | (() => S)
mutations?: MutationTree<S>
actions?: ActionTree<S,R>
context: ActionContext<S,R>
store?: Store<any>
constructor(module: Mod<S,any>)
}
export type ConstructorOf<C> = {
new (...args: any[]): C
}
export function getModule<M extends VuexModule>(
moduleClass: ConstructorOf<M>,store?: Store<any>
): M
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。