定义:

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式
简单的理解为一个管理数据的根对象

主要内容:

首先在Vue实例中提前创建好store

  1. new Vue({
  2. el: '#app',
  3. store: store, // ES6语法可简写为store
  4. })

然后就可以在任何一个组件中使用
this.$store.commit('方法名')来调用方法
this.$store.state.xxx来获取数据

state:数据(设置一个初始值即可)

mutations:所有的方法都放这里(都有一个事件类型和回调函数),必须是同步函数

这个回调函数会接受state作为第一个参数
更改store的状态的方法就是提交mutations

  1. const store = new Vuex.Store({
  2. state: {
  3. count: 1
  4. },
  5. mutations: {
  6. add (state) {
  7. // 变更状态
  8. state.count++
  9. }
  10. }
  11. })

不能直接调用其方法,需要使用store.commit('add'),外部组件使用this.$store.commit('add')

参数的形式:可以额外传参(仅能传两个参数,如有第三个使用对象传参)

add(state,n){}
add(state,payload: {m,n}) 整个对象作为第二个参数

actions:提交mutations,而不是直接变更状态(可以包含任意异步操作)

  1. actions: {
  2. add (context) {
  3. context.commit('add')
  4. }
  5. }
  6. // 参数解构
  7. actions: {
  8. add ({ commit }) {
  9. commit('add')
  10. }
  11. }

调用:store.dispatch('add')

modules

store里面内容也可以分为多个模块,每个模块中又都分为state、mutations、actions

模块的局部状态:

  • 对于模块内部的 mutation 和 getter,接收的第一个参数是模块的局部状态对象(局部的state)
  • 对于模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState
  • 对于模块内部的 getter,根节点状态会作为第三个参数暴露出来 ```javascript const moduleA = { state: () => ({ … }), mutations: { … }, actions: { … }, getters: { … } }

const moduleB = { state: () => ({ … }), mutations: { … }, actions: { … } }

const store = new Vuex.Store({ modules: { a: moduleA, b: moduleB } })

store.state.a // -> moduleA 的状态 store.state.b // -> moduleB 的状态 ```