Vuex 中提供了四个辅助函数,用来帮助我们更方便的去获取仓库中的数据和方法。
mapState:获取 state 中数据mapGetters:获取 getters 中的计算属性mapMutations:获取 mutations 中的方法mapActions:获取 actions 中的方法一、引入
在组件中,使用辅助函数之前,都需要先引入:import { mapState, mapGetters, mapMutations, mapActions } from 'vuex';
二、使用
辅助函数的使用可以分为两类:
- 在 computed 中调用的辅助函数:mapState 和 mapGetters;
- 在 methods 中调用的辅助函数:mapMutations 和 mapActions;
语法结构:
export default {computed: {...mapState(['数据名', '数据名']),...mapGetters(['计算属性名', '计算属性名']),// 组件自己的计算属性},methods: {...mapMutations(['方法名', '方法名']),...mapActions(['方法名', '方法名'])}}
说明:
- 在
computed调用辅助函数,获取到的所有数据,都会变成组件自己的计算属性; - 在
methods调用辅助函数,获取到的所有方法,都会变成组件自己的方法;
