mapState和mapGetters是Vuex提供的辅助函数,用于将store的state和getter映射到组件computed属性,支持数组/对象写法及命名空间模块;需通过commit/dispatch修改状态。

在 Vue 2 中,mapState 和 mapGetters 是 Vuex 提供的辅助函数,用来把 store 中的状态和 getter 映射到组件的计算属性里,避免手动写冗长的 this.$store.state.xxx 或 this.$store.getters.xxx。用得好,代码更简洁、可读性更强。
mapState:快速映射 state 到 computed
mapState 适用于直接读取 Vuex store 的 state 属性。它支持数组写法和对象写法,推荐用对象写法,便于起别名或添加逻辑。
- 数组写法(适合字段名与 state 键名一致):
<script>
import { mapState } from 'vuex'
export default {
computed: mapState(['count', 'userInfo'])
}
</script>
- 对象写法(支持重命名、计算逻辑):
computed: mapState({
// 直接映射
count: state => state.count,
// 重命名(比如把 cartItems 改成 cart)
cart: state => state.cartItems,
// 带逻辑处理
hasItems: state => state.cartItems.length > 0
})
注意:箭头函数里的 state 指的是根 state;如果用了命名空间模块,需配合命名空间前缀(见下文)。
mapGetters:简化 getter 调用
mapGetters 用法和 mapState 类似,但映射的是 store 中定义的 getters。它同样支持数组和对象两种写法。
立即学习“前端免费学习笔记(深入)”;
- 数组写法(简单场景):
computed: mapGetters(['doneTodos', 'cartTotalPrice'])
- 对象写法(支持别名):
computed: mapGetters({
finished: 'doneTodos',
total: 'cartTotalPrice'
})
getter 本质是带缓存的计算属性,适合封装派生状态(如过滤、统计),比在组件里重复写逻辑更可靠。
配合命名空间模块使用
当 store 分模块且启用了 namespaced: true,必须显式指定模块路径,否则会找不到。
- 映射某模块的 state:
computed: mapState('user', ['name', 'avatar'])
- 映射某模块的 getter:
computed: mapGetters('product', ['onSaleList', 'topRated'])
- 对象写法中带命名空间(更清晰):
computed: {
...mapState('cart', ['items']),
...mapGetters('cart', { cartSize: 'size' })
}
组合使用 + 注意事项
实际开发中,通常把 mapState、mapGetters 和组件自身计算属性一起用,用展开运算符合并:
computed: {
...mapState(['count']),
...mapGetters(['doneCount']),
// 自定义计算属性
isBusy() { return this.count > 100 }
}
- 不要在
mapState或mapGetters里写副作用(如调用 API),它们只用于响应式读取 - 映射后的属性是只读的,修改它们不会影响 store;要改状态,必须通过
commit或dispatch - 确保已正确安装 Vuex 并在根实例传入
store,否则会报$store is undefined


















