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

Vuex 的核心概念

1. State(状态)

Vuex 的核心是 state,它是一个包含所有组件状态的对象。

2. Getter(获取器)

类似于 Vue 的 computed 属性,getter 可以从 state 中派生出一些状态。

3. Mutation(突变)

Mutation 是改变状态的唯一方式,并且它是同步的。

4. Action(行为)

Action 提供了一种提交 mutation 的方式,可以包含任意异步操作。

5. Module(模块)

Vuex 允许我们将 store 分割成模块。

Vuex 的使用

  1. 安装 Vuex

    npm install vuex --save
    
  2. 创建 Vuex 实例

    import Vue from 'vue'
    import Vuex from 'vuex'
    
    Vue.use(Vuex)
    
    const store = new Vuex.Store({
      state: {
        count: 0
      },
      mutations: {
        increment(state) {
          state.count++
        }
      },
      actions: {
        increment(context) {
          context.commit('increment')
        }
      }
    })
    
    new Vue({
      el: '#app',
      store,
      render: h => h(App)
    })
    
  3. 在组件中使用 Vuex

    export default {
      computed: {
        count() {
          return this.$store.state.count
        }
      },
      methods: {
        increment() {
          this.$store.dispatch('increment')
        }
      }
    }
    

扩展阅读

想要更深入地了解 Vuex,可以阅读官方文档:Vuex 官方文档

图片展示

Vuex 中的 State

State

Vuex 中的 Getter

Getter

Vuex 中的 Mutation

Mutation

Vuex 中的 Action

Action

Vuex 中的 Module

Module