使用vuex时,如何在typescript语法中使用mapState函数?
我在与vuex集成的vuejs项目中使用typescript语法。 我想使用在.ts文件中计算的mapState方法,但出现语法错误。 目前我正在使用docs建议的计算函数语法,我的意思是:使用vuex时,如何在typescript语法中使用mapState函数?,typescript,vuejs2,vuex,Typescript,Vuejs2,Vuex,我在与vuex集成的vuejs项目中使用typescript语法。 我想使用在.ts文件中计算的mapState方法,但出现语法错误。 目前我正在使用docs建议的计算函数语法,我的意思是: get counter() { return this.$store.state.count; } 如果阅读Vuex文档,您会发现以这种方式使用Vuex而不是使用mapState是非常重复的。在大型应用程序中使用mapState非常简单和有用。我想在我的Typescript组件中使用mapSt
get counter() {
return this.$store.state.count;
}
如果阅读Vuex文档,您会发现以这种方式使用Vuex而不是使用mapState
是非常重复的。在大型应用程序中使用mapState
非常简单和有用。我想在我的Typescript组件中使用mapState
,但我不知道正确的方法。我尝试了下面的方法来使用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
}
更容易使用JS:
但是,如何使用组件注释调用多个模块的mapState(例如)?您正在定义的变量名为“computed”是否重要?@belvederef只需多次调用它“```组件({//如果您没有使用名称空间的计算模块,请省略名称空间参数('myModule'):{…mapState('myModule',['count',]),…mapState('anotherModule',['count',]),})
<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: {
},
});