【问题标题】:How to use mapState function in typescript syntax when using vuex?使用 vuex 时如何在 typescript 语法中使用 mapState 函数?
【发布时间】:2019-01-03 04:20:00
【问题描述】:

我在与 vuex 集成的 vuejs 项目中使用 typescript 语法。 我想使用在我的 .ts 文件中计算的 mapState 方法,但出现语法错误。 目前我正在使用文档建议的计算函数语法,我的意思是:

 get counter() {
   return  this.$store.state.count;
 }

如果您阅读 Vuex 文档,您会发现以这种方式使用 Vuex 而不是使用mapState 是非常重复的。在大型应用程序中使用mapState 非常简单且有用。我想在我的 Typescript 组件中使用mapState,但我不知道正确的方法。我尝试了下面的方法来使用mapState 函数,但没有成功。

get mapState({
  counter:count
});

// or

get mapState(['name', 'age', 'job'])

如果有人可以帮助我,我将不胜感激。

【问题讨论】:

    标签: typescript vuejs2 vuex


    【解决方案1】:

    你可以在组件注解中调用 mapState:

    import { Component, Vue } from 'vue-property-decorator';
    import { mapState } from 'vuex';
    
    @Component({
      // omit the namespace argument ('myModule') if you are not using namespaced modules
      computed: mapState('myModule', [ 
        'count',
      ]),
    })
    export default class MyComponent extends Vue {
      public count!: number; // is assigned via mapState
    }
    

    您也可以使用 mapState 根据您的状态创建新的计算:

    import { Component, Vue } from 'vue-property-decorator';
    import { mapState } from 'vuex';
    import { IMyModuleState } from '@/store/state';
    
    @Component({
      computed: mapState('myModule', {
        // assuming IMyModuleState.items
        countWhereActive: (state: IMyModuleState) => state.items.filter(i => i.active).length,
      }),
    })
    export default class MyComponent extends Vue {
      public countWhereActive!: number; // is assigned via mapState
    }
    

    【讨论】:

    • 但是如何使用组件注解来调用多个模块,例如,mapState?您定义的变量称为“计算”是否重要?
    • @belvederef 只需多次调用它 ``` @Component({ // 如果您不使用命名空间模块,请忽略命名空间参数 ('myModule'): { ...mapState('myModule) ', ['count',]), ...mapState('anotherModule', ['count',]), } })
    【解决方案2】:

    更容易使用 JS Spread syntax:

    <template>
      <div class="hello">
        <h2>{{ custom }}</h2>
        </div>
    </template>
    
    <script lang="ts">
    import { Component, Prop, Vue } from 'vue-property-decorator';
    import { mapState } from 'vuex';
    
    @Component({
      computed: {
        ...mapState({
          title: 'stuff'
        }),
        // other stuff
      },
    })
    export default class HelloWorld extends Vue {
    
      title!: string;
    
      public get custom():string {
        return this.title;
      }
    }
    </script>
    

    您的商店:

    import Vue from 'vue';
    import Vuex from 'vuex';
    
    Vue.use(Vuex);
    
    export default new Vuex.Store({
      state: {
        stuff: 'some title',
      },
      mutations: {
    
      },
      actions: {
    
      },
    });
    

    【讨论】:

      猜你喜欢
      • 2021-09-13
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      • 2018-12-08
      • 2022-01-11
      • 2018-01-17
      • 2021-07-17
      • 2019-05-23
      相关资源
      最近更新 更多