Vuex 简介

Vuex 是一个专门针对 Vue.js 应用的状态管理库,它可以让我们更方便地管理应用中的数据和状态,从而达到更好的代码组织和代码复用的效果。

Vuex 中的核心元素有四个:state、getters、mutations 和 actions。

state

Vuex 中的状态存储在 state 对象中。State 中的状态是响应式的,当组件引用这些状态时,如果状态发生变化,组件也会自动更新。

getters

Getters 可以让我们派生出一些状态,这些状态不需要像 State 一样被存储在 store 中,而是可以从 Store 中的现有状态中计算出来。Getter 有两个作用:缓存和派生。

mutations

Mutations 是 Vuex 中专门用于更新状态的方法。我们不能直接修改 Store 中的状态,而是需要通过提交 Mutations 来改变状态。Mutation 中的方法必须是同步的,这也是它们的一个限制。

actions

Actions 可以看作是 Mutations 的异步版本。通过 Actions,我们可以在应用中执行异步操作,例如从后端 API 获取数据,然后将响应数据提交到 Mutations 中去更新状态。由于 Actions 支持异步操作,它可以帮助我们进行一些比较复杂的业务逻辑处理。

在项目中使用 Vuex

要在项目中使用 Vuex,我们需要执行以下步骤:

  1. 安装 Vuex:在项目中执行 npm install vuex 命令;
  2. 创建一个状态管理实例,通常命名为 store:Vue.js + Vuex 项目一般会在 main.js 中创建;
  3. 在 store 实例中声明 state、getters、mutations、actions,并在组件中引用 Store 中的状态。

举个例子,假设我们需要在一个组件中展示一个计数器,并且希望当点击按钮时,计数器增加 1。首先我们需要在 Store 中声明计数器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// store.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++;
}
},
actions: {
increment(context) {
context.commit('increment');
}
},
getters: {
doubleCount(state) {
return state.count * 2;
}
}
});

在组件中,我们需要引用 Store 中的 state 和 mutations:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Counter.vue
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>

<script>
import { mapState, mapMutations } from 'vuex';

export default {
computed: {
...mapState(['count'])
},
methods: {
...mapMutations(['increment'])
}
};
</script>

上面的代码中,我们使用 mapStatemapMutations 辅助函数来简化代码,这两个函数可以将 Store 中的状态映射到组件的计算属性和方法中,使代码更加简洁。