Vue基础知识总结 14:Vuex是做什么的?

一、官方解释

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

二、Vuex状态管理图例

三、VueX的核心概念

  1. State
  2. Getters
  3. Mutation
  4. Action
  5. Module

四、getters

从store中获取一些state变异后的状态。

export default  {
          
   
  powerCounter(state) {
          
   
    return state.counter * state.counter
  },
  more20stu(state) {
          
   
    return state.students.filter(s => s.age > 20)
  },
  more20stuLength(state, getters) {
          
   
    return getters.more20stu.length
  },
  moreAgeStu(state) {
          
   
    return age => {
          
   
      return state.students.filter(s => s.age > age)
    }
  }
}

五、Mutation

Vuex的store状态的更新唯一方式:提交Mutation

Mutation主要包括两部分:

  1. 字符串的事件类型;
  2. 一个回调函数(handler),该回调函数的第一个参数就是state; Mutation的定义方式:
mutations: {
          
   
    increment(state) {
          
   
      state.count++
    }
  },

通过Mutation更新:

increment:function() {
          
   
      this.$store.commit(increment)
    }

在通过Mutation更新数据的时候,有可能带参数,参数被称为Mutation的载荷(Payload)。

increment(state, x){
          
   
	state.count += x;
}
increment: function(){
          
   
	this.$store.commit(increment, x)
}

如果是多个对象呢?

那么可以在以对象的方式传递。

六、Action

代替Mutation进行异步操作。

actions: {
          
   
    increment(context) {
          
   
      setTimeout(() => {
          
   
        context.commit(increment)
      }, 1000)
    }
  }

context是什么?

context是和store对象具有相同方法和属性的对象,也就是说可以通过context进行commit,也可以获取context.state。

在Vue组件中,如果我们调用action中的方法,那么就需要使用dispatch方法。

actions: {
          
   
    increment(context) {
          
   
      setTimeout(() => {
          
   
        this.$store.dispatch(increment)
      }, 1000)
    }
  }

action返回的Promise。

在Action中,我们可以将异步操作放在一个Promise中,并且在成功或失败后,调用对应的resolve或reject。

actions: {
          
   
    increment(context) {
          
   
        return new Promise((resolve => {
          
   
			setTimeout(() => {
          
   
		        context.commit(increment)
		      }, 1000)	
		}))
    }
  }

七、Module

Vue将store分割成多个module,每个模块拥有自己的state、mutations、actions、getters等。


经验分享 程序员 微信小程序 职场和发展