用Vuex来做vue应用的状态管理

什么是Vuex

Vuex是一个专为Vue.js应用程序开发的状态管理模式。

当我们的Vue应用越来越大的时候,有一些公用部分的状态不好管理,比如多重组件嵌套等。这时候,我们就可以用Vuex来进行统一的应用状态管理。

核心概念

State (读)

State是唯一的数据源,单一状态树

this.$store.state.count

Mutations (写)

更改Vuex的store中的状态的唯一方法是提交mutation,Mutation 必须是同步函数。

1
2
3
4
5
6
7
8
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
store.commit('increment', {
amount: 10
})

Actions

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})

Getters

通过Getters可以派生出一些新的状态(在state的基础上)

1
2
3
4
5
6
7
8
9
10
11
12
13
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)
}
}
})

Modules

面对复杂的应用程序,当管理的状态比较多时,我们需要将Vuex的store对象分割成模块(modules)。

例子

你可以通过 store.state 来获取状态对象,以及通过 store.commit 方法触发状态变更。

最主要的是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
27
28
Vue.use(Vuex);

const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment: state => state.count++,
decrement: state => state.count--
}
})

new Vue({
el: '#app',
computed: {
count () {
return store.state.count
}
},
methods: {
increment () {
store.commit('increment')
},
decrement () {
store.commit('decrement')
}
}
})