computed: {
count () {
return this.$store.state.count
}
}
}
mapState函数
computed: {
count () {
return this.$store.state.count
}
}
上面通过count计算属性获取同名state.count属性,如何每一次获取都要写一个这样的方法,是不显得重复又麻烦?可以使用mapState函数简化这个过程。
import { mapState } from 'vuex';export default {
computed: mapState ({
count: state => state.count,
countAlias: 'count', // 别名 `count` 等价于 state => state.count
})
}
还有更简单的使用方法:
computed: mapState([
'count'
// 映射 this.count 为 store.state.count
])Getters对象
如果我们需要对state对象进行做处理计算,如下:
computed: {
doneTodosCount () {
return this.$store.state.todos.filter(todo => todo.done).length
}
}
如果多个组件都要进行这样的处理,那么就要在多个组件中复制该函数。这样是很没有效率的事情,当这个处理过程更改了,还有在多个组件中进行同样的更改,这就更加不易于维护。
Vuex中getters对象,可以方便我们在store中做集中的处理。Getters接受state作为第一个参数:
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
] },
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
})在Vue中通过store.getters对象调用:
computed: {
doneTodos () {
return this.$store.getters.doneTodos
}
}Getter也可以接受其他getters作为第二个参数:
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
},
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}mapGetters辅助函数
与mapState类似,都能达到简化代码的效果。mapGetters辅助函数仅仅是将store中的getters映射到局部计算属性:
import { mapGetters } from 'vuex'export default {
// ...
computed: {
// 使用对象展开运算符将 getters 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}










