我在与 vuex 集成的 vuejs 项目中使用 typescript 语法。
我想使用 .ts 文件中计算的 mapState 方法,但出现语法错误。
目前我正在使用文档建议的计算函数语法,我的意思是:
get counter() {
return this.$store.state.count;
}
如果你阅读 Vuex 文档,你会发现以这种方式使用 Vuex 而不是使用mapState
非常重复。使用mapState
在大型应用程序中非常简单且有用。我想用mapState
在我的 Typescript 组件中,我不知道正确的方法。我尝试过下面的方法来使用mapState
功能,但没有用。
get mapState({
counter:count
});
// or
get mapState(['name', 'age', 'job'])
如果有人能帮助我,我将不胜感激。
您可以在组件注释中调用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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)