【问题标题】:Creating reusable getters in vuex-module-decorators在 vuex-module-decorators 中创建可重用的 getter
【发布时间】:2020-03-15 21:01:18
【问题描述】:

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

我是这样试过的:

我的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.js vuex


    【解决方案1】:

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

    你可以这样做:

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

    【讨论】:

    • 谢谢你的回答,但是 vuex-module-decorators 用于整个项目来输入 vuex,所以我也应该在我的情况下使用它。
    【解决方案2】:

    我遇到了同样的问题,并找到了“vuex-class-modules”数据包的解决方案。它有类似的装饰器。

    export class LoadItems extends VuexModule {
        public items = [];
        
        @Mutation
        public SET_ITEMS(...
        
        @Action
        public getItems() {
            this.SET_ITEMS(['hello', 'world'])
        }
    

    在您的孩子中扩展此类后:

    @Module
    class Contract extends LoadItems {
       // your additional code here
    }
    export const ContractModule = new Contract({ store, name: "contract" });
    

    现在您可以使用命令获取任何语句并调用任何操作:

    ContractModule.getItems();
    

    当然,你必须先导入它。

    【讨论】:

      猜你喜欢
      • 2020-03-07
      • 2019-09-07
      • 2021-11-14
      • 2019-09-14
      • 2021-01-06
      • 2020-06-05
      • 2021-06-18
      • 2020-11-05
      • 2021-05-29
      相关资源
      最近更新 更多