首页 > 解决方案 > 在 vuex-module-decorators 中创建可重用的 getter

问题描述

使用 vuex-module-decorators 遇到这样的问题。我想创建一些父模块,以便子模块可以从中扩展并继承它的动作和吸气剂。但是吸气剂不是继承的。

我是这样尝试的:

我的parent-module.ts

import {Action, getModule, Module, Mutation, VuexModule} from 'vuex-module-decorators';

export class ParentStore extends VuexModule {
    public get getterForInherit(): any {
        return someData
    }
}

子模块 child-one.ts

import {Action, getModule, Module, Mutation, VuexModule} from 'vuex-module-decorators'
import {ParentModule} from './parent-module';

@Module({dynamic: true, store: Store, name: 'childOne', namespaced: true})
class FirstChildModule extends ParentModule {
    public get SecondChildGetter(): number {
        return 1;
    }
}

export const FirstChildStore: ParentModule = getModule(FirstChildModule)

child-two.ts

import {Action, getModule, Module, Mutation, VuexModule} from 'vuex-module-decorators'
import {ParentModule} from './parent-module';

@Module({dynamic: true, store: Store, name: 'childTwo', namespaced: true})
class SecondChildModule extends ParentModule {
    public get FirstChildGetter(): number {
        return 2;
    }
}

export const SecondChildStore: ParentModule = getModule(SecondChildModule)

但是当我将这些模块导入组件时getterForInherit不可用。有可能这样做吗?

标签: vue.jsvuex

解决方案


我认为与其尝试使用不同的包来处理您的突变、动作和吸气剂;根据您的问题,我假设您希望能够从父组件或子组件访问您的 getter 和操作。如果您已经安装了 vuex,则可以使用它。

你可以这样做:

import { mapGetters, mapActions, mapMutations } from 'vuex'
methods: {
...mapActions(['submitTransaction', 'submitNotification']),
...mapMutations(['clearNotificationData']),
},
computed: {
...mapGetters([
  'messageData',
  'isMessageLoaded',
  'isProcessingRequest',
]),

推荐阅读