使用 vuex 时如何在打字稿语法中使用 mapState 函数? [英] How to use mapState function in typescript syntax when using vuex?

查看:34
本文介绍了使用 vuex 时如何在打字稿语法中使用 mapState 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using typescript syntax in my vuejs project that integrated with vuex. I want to use mapState method as computed in my .ts file but I got a syntax error. Currently I am using docs suggested syntax for computed function, I mean:

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

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

If you read the Vuex docs you will see that using Vuex in this way instead of using mapState is very repetitive. Using mapState is very easy and useful in large applications. I want to use mapState in my Typescript component and I don't know the right way. I've tried the way below to use the mapState function and it didn't work.

get mapState({
  counter:count
});

// or

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

如果有人能帮助我,我将不胜感激.

I'd be grateful if someone could help me.

推荐答案

您可以在 Component 注解中调用 mapState:

You may call mapState within the Component annotation:

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 根据您的状态创建新的计算:

You may also use mapState to create new computeds based off of your state:

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
}

这篇关于使用 vuex 时如何在打字稿语法中使用 mapState 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆