vuex自己的理解

先上一张流程图

我的理解:

首先components(组件)通过dispatch方法触发actions(这里可以进行异步的操作比如后台取数据)

然后actions通过commit()方法触发mutations(这里更改state中的数据但只能进行同步操作)

最后state中的数据更新后展示在components(组件)

官网说vuex有5个核心概念:

state getter mutation action module

一.state

用于存放需要管理的数据,数据的结构根据项目自己设计,大概长这个样:

const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ],
    isShow: true,
    num: 0
  }
})

二.getter

用于获取state里面的数据。
getters是一个对象用于存放多个方法类似于计算属性需要放到计算属性里。
方法接受state作为参数返回state中的数据,
也可以接受其他getter作为第二个参数。

const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
  }
})

三.mutation

用于更改state中的数据。mutations是一个对象用于存放多个方法类似于事件,
方法接受state作为参数。方法不能直接调用,需要通过store.commit()的触发,方法名就是参数。
store.commit('increment')
可以在组件中使用 this.$store.commit('xxx') 提交 mutation

也可以有额外的参数如下:

mutations: {
  increment (state, n) {
    state.count += n
  }
}
// 触发
store.commit('increment', 10)

可以用常量替代mutations事件类型

// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'
// store.js
import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'

const store = new Vuex.Store({
  state: { ... },
  mutations: {
    // 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
    [SOME_MUTATION] (state) {
      // mutate state
    }
  }
})

四.action

类似于 mutation,不同在于:
Action 提交的是 mutation,而不是直接变更状态。
Action 可以包含任意异步操作。

// 触发方式
this.$store.dispatch('increment')

actions: {
  increment (context) {
    context.commit('increment')
  }
}

上面代码中的increment就是mutation中的方法。

Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象
因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。

五.module

const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: { ... },
  mutations: { ... },
  actions: { ... }
}

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

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

目录结构:

store:

单个module:

main.js:

原文地址:https://www.cnblogs.com/gr07/p/8669463.html