Vuex是干什么的?以及核心概念
- Vuex是专门为Vue.js设计的状态管理模式。它采用集中式储存管理Vue应用中所有组件的状态
- Vuex的核心概念:
. State --> 数据源存放地 ,类似vue组件中的data,在组件中通过store.state可以访问
. Getter --> 类似于vue组件中的计算属性,接受state作为第一个参数也接受其他的getter作为第二个参数,在组件中可以以访问state的方式访问store.getters,也可以使用mapGetters辅助函数computed{ // 使用对象展开运算符将 getter 混入 computed 对象中 ...mapGetters([ 'doneTodosCount', ..... ]) }
. Mutation --> 更改Vuex中State的唯一方法就是提交一个Mutation,非常类似于事件,每个mutation都有一个事件类型和一个回调函数,这个回调函数实际就是我们进行状态更改的地方,接受state作为第一个参数,注意mutation必须是同步函数mutations:{ increment (state,payload){ state.count += payload.amount } }
触发时传入额外的参数:store.commit('increment ', { amount: 10 })
或者store.commit({ type: increment , amount: 10 })
在组件中提交mutationsimport { mapMutations } from 'vuex'
methods: { ... mapMutations ([ 'increment' // 将 this.increment()映射为 this.$store.commit('increment') ]) }
. Action --> action类似于mutation,但是不同的是action提交的是mutation,而不是直接的去改变状态,action可以包含任意的异步操作,接受一个与store相同方法和属性的context对象
actions: { incrementAsync({ commit }) { commit('increment') } }
或者actions: { incrementAsync(context) { context.commit('increment') } }
actions通过store.dispatch('incrementAsync')
方法触发 ,或者传递额外参数store.dispatch(‘incrementAsync’, payload)
或者store.dispatch({ type: 'incrementAsync', amount: 10 })
在组件中触发action:methods: { ...mapActions(['incrementAsync' // 将 this.incrementAsync() 映射为 this.$store.dispatch('incrementAsync')]) }
. Module–> 由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割