Vuex的核心概念

State

State提供唯一的公共数据源,所有共享的数据都要统一放到Store的State中进行存储

const store = new Vuex.Store({
  state:  { count: 0 }
})
组件访问State中数据的第一种方式:
this.$store.state.count
组件访问State中数据的第二种方式:

通过导入mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性

import { mapState } from 'vuex'

computed:{
...mapState(['count'])
}

Mutation

mutation用于变更Store的数据

  • 只能通过mutation变更Store数据,不可以直接操作Store中的数据
  • 可以集中监控所有数据的变化
  • 只能写同步代码
const store = new Vuex.Store({
  state:  { count: 0 },
//定义Mutation
  mutations: {
    ADD_COUNT: (state) => {
      state.count++
    },
    //传递参数
   ADD_NCOUNT: (state, step) => {
      state.count =+ step
    }
  }
})
触发mutation的第一种方式
this.$store.commit('ADD_COUNT')
this.$store.commit('ADD_NCOUNT',3) // 传递参数 
触发mutation的第二种方式:

通过导入mapMutations函数,将需要的mutations函数,映射为当前组件的methods方法

import { mapMutations } from 'vuex'

methods:{
...mapMutations([ 'ADD_COUNT', 'ADD_NCOUNT' ])
//使用 this.ADD_COUNT() this.ADD_NCOUNT(3)
}

Action

如果通过异步操作变更数据,必须通过Action,而不能使用Mutation,但是Action中还是要通过触发Mutation的方式间接变更数据

const store = new Vuex.Store({
 state:  { count: 0 },
//定义Mutation
 mutations: {
   ADD_COUNT: (state) => {
     state.count++
   },
   //传递参数
   ADD_NCOUNT: (state, step) => {
     state.count =+ step
   }
 },
 actions:{
   addAsync({commit}) {
    setTimeout( () => {
      commit('ADD_COUNT')
     },1000) 
   }
 }
})
触发Action的第一种方式
this.$store.dispatch('addAsync')
触发Action的第二种方式

通过导入mapActions函数,将需要的actions函数,映射为当前组件的methods方法

import { mapActions} from 'vuex'

methods:{
...mapActions([ 'addAsync' ])
//使用 this.addAsync()
}

Getter

  • Getter可以对Store中已有的数据加工处理形成新的数据,类似Vue的计算属性
  • Store中数据发生变化,Getter的数据也会跟着变化
const store = new Vuex.Store({
  state:  { count: 0 },
//定义Mutation
  mutations: {
    ADD_COUNT: (state) => {
      state.count++
    },
    //传递参数
    ADD_NCOUNT: (state, step) => {
      state.count =+ step
    }
  },
  actions:{
    addAsync({commit}) {
     setTimeout( () => {
       commit('ADD_COUNT')
      },1000) 
    }
  },
  getters:{
    showCount: state => state.count
  }
})
使用getters的第一种方式
this.$store.getters.showCount

你可能感兴趣的:(Vuex的核心概念)