🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 一、适用情况 >[danger] > 1、一般情况下,只有组件之间共享的数据,才有必要存储到vuex中,对于组件中私有的数据,存储在组件自身的data中; > 2、全局单例模式管理,某个状态,全局共享方可纳入; > 3、如果有些状态严格属于单个组件,最好还是作为组件的局部状态; ## 二、访问State方式 1、直接访问this.$store.state.全局数据名称 ~~~ computed: { count () { return store.state.count } } ~~~ 2、mapState将当前组件需要的全局数据,映射为当前组件的计算属性 ~~~ // 从vuex中按需导入mapState函数 import {mapState} from 'vuex' ...... // 将全局数据,映射为当前组件的计算属性 computed: { ...mapState(['count']) } ~~~ ## 三、修改State 1. **只能**通过`mutation`变更`Store`数据,不可以直接操作`Store`中的数据。 2. 通过这种方式虽然操作起稍微繁琐一些,但是可以集中监控所有数据的变化; 3. action实际上也还是调用mutation来变更store数据; ## 四、使用Getters的方式 1、直接使用this.$store.getters.名称; ~~~ computed: { doneTodosCount () { return this.$store.getters.doneTodosCount } } ~~~ 2、mapGetters将需要的getters直接映射到组件的计算属性中,直接使用; ~~~ import { mapGetters } from 'vuex' computed: { ...mapGetters(['showNum']) } ~~~ ## 五、触发Mutations(同步操作)方式 1、直接调用this.$store.commit(); ~~~ methods: { add(){ this.$store.commit('increment') } } ~~~ 2、mapMutations将需要的`mutations`函数,映射为当前组件的`methods`方法,就可以直接在methods方法里面调用了; ~~~ // 从vuex中按需导入mapMutations函数 import {mapMutations} from 'vuex' ...... methods: { ...mapMutations(['add','addN']) } ~~~ ## 六、触发Action(异步操作)方式 1、直接调用this.$store.dispatch; ~~~ methods: { add(){ this.$store.dispatch('increment') } } ~~~ 2、mapActions将需要的`actions`函数,映射为当前组件的`methods`方法,就可以直接在methods方法里面调用了; ~~~ // 从vuex中按需导入mapActions函数 import {mapActions} from 'vuex' ...... methods: { ...mapActions(['addAsync','addNASync']) } ~~~