当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键:
// 对象形式
computed:{
...mapState({
count: state => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count'
})
}
// 数组形式:当映射的计算属性名称和 state 里面一样时
computed:{
// 映射 this.count 为 store.state.count
...mapState(['count'])
}
与 mappState 类似,mapGetters 也可以让你映射组件的 getter 属性:
// 对象形式
computed:{
...mapGetters({
// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
doneCount: 'doneTodosCount'
})
}
// 数组形式
computed: {
...mapGetters([
'doneTodosCount',
'anotherGetter',
])
}
使用常量替代 mutation 事件类型在各种 Flux 实现中是很常见的模式。这样可以使 linter 之类的工具发挥作用,同时把这些常量放在单独的文件中可以让你的代码合作者对整个 app 包含的 mutation 一目了然:
// mutation-types.js
export const SOME_MUTATION = "SOME_MUTATION";
// store.js
import { createStore } from 'vuex'
import { SOME_MUTATION } from './mutation-types'
const store = createStore({
state: { ... },
mutations: {
// 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
[SOME_MUTATION] (state) {
// 修改 state
}
}
})
methods: {
...mapMutations([
'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
]),
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
})
}
import { mapActions } from "vuex";
export default {
// ...
methods: {
...mapActions([
"increment" // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
]),
...mapActions({
add: "increment" // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}
};
computed: {
...mapState({
a: state => state.someModule.a,
b: state => state.someModule.b
})
},
methods: {
...mapActions([
'someModule/foo', // -> this['someModule/foo']()
'someModule/bar' // -> this['someModule/bar']()
])
}
开启模块及命名空间之后,Vuex 辅助函数的第一个参数为模块名称
computed: {
...mapState('someModule', {
a: state => state.a,
b: state => state.b
})
},
methods: {
...mapActions('someModule', [
'foo', // -> this.foo()
'bar' // -> this.bar()
])
}






