vuex 五大核心概念

480 阅读1分钟

vuex是什么

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理数据,以相应的规则保证状态以一种可预测的方式发生变化

五大核心概念

state 共享数据源

直接使用:this.$store.state.变量名 // 不分模块
             this.$store.state.模块名.变量名 // 分模块
映射使用:import { mapState } from 'vuex'
             export default {
              computed: {
                ...mapState(['state变量名']) // 不分模块
                ...mapState('模块名', ['state变量名']) // 分模块
              }
             }

mutations 同步任务,唯一可以修改state数据的地方

直接使用:this.$store.commit('mutations方法名', 具体值) // 不分模块
             this.$store.commit('模块名/mutations方法名', 具体值) // 分模块
    
映射使用:import { mapMutations } from 'vuex'
             export default {
              computed: {
                ...mapMutations(['mutations方法名']) // 不分模块
                ...mapMutations('模块名', ['mutations方法名']) // 分模块
              }
             }

actions 异步任务,修改数据源先提交到 mutations

直接使用:this.$store.dispatch('actions方法名', 具体值) // 不分模块
             this.$store.dispatch('模块名/actions方法名', 具体值) // 分模块
    
映射使用:import { mapActions } from 'vuex'
             export default {
              computed: {
                ...mapActions(['actions方法名']) // 不分模块
                ...mapActions('模块名', ['actions方法名']) // 分模块
              }
             }

getters vuex中的计算属性

直接使用:this.$store.getters.计算属性名 // 不分模块
             this.$store.getters['模块名/计算属性名'] // 分模块
    
映射使用:import { mapGetters } from 'vuex'
             export default {
              computed: {
                ...mapGetters(['计算属性名']) // 不分模块
                ...mapGetters('模块名', ['计算属性名']) // 分模块
              }
             }

modules 分模块

modules: {}