Vuex的辅助方法
vuex有五个核心的概念,分别为State、Getter、Mutation、Action、Module。而我们在组件中获取vuex中的数据或者使用方法更改数据时,都是直接使用一下的方法:
this.$store.state.xxx;
this.$store.commit('xxx');
this.$store.dispatch('xxx')
但是随着业务功能逐渐增加,会出现很多个状态。当一个组件需要多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。
于是vuex提供了一些辅助函数,比如mapState、mapGetter、mapMutation、mapAction来简化。
mapState()
mapstate()是对state对象进行的二次计算,他可以简化我们的代码。
import { mapState } from 'vuex';
export default {
computed:{
...mapState({
'num',
'id'
})
}
原本在组件中需要使用
this.$store.state.num来引用num
而现在使用了mapState直接可以插值;
{{num}}
mapMutations
import { mapMutations} from 'vuex';
export default{
methods:{
...mapMutations([
'add',
'subtract'
])
}
}
将this.add映射为this.$store.commit('add') ;
在组件使用this.add就相当于使用this.$store.commit('add')
mapActions
import { mapActions} from 'vuex';
export default{
methods:{
...mapActions({
'add': 'increment' //改名
})
}
}
将this.add映射为this.$store.dispatch('increment');
mapGetters
import { mapGetters} from 'vuex';
export default {
computed:{
...mapGetters({
'get'
}),
}
}
将this.get映射为this.$store.getters('get');