2
2
3
3
为了更好地理解 Vuex app 中的数据流,我们来开发一个简单的计数器 app。注意:这个例子仅仅是为了更好地解释概念,在实际情况中并不需要在这种简单的场合使用 Vuex.
4
4
5
- ### 引入并加载 Vuex
5
+ ### Store
6
6
7
7
``` js
8
8
// store.js
9
9
import Vue from ' vue'
10
10
import Vuex from ' vuex'
11
11
12
12
Vue .use (Vuex)
13
- ```
14
-
15
- ### 定义 App State
16
13
17
- ``` js
14
+ // 应用初始状态
18
15
const state = {
19
16
count: 0
20
17
}
21
- ```
22
-
23
- ### 定义会被用到的 State Mutations
24
18
25
- ``` js
19
+ // 定义所需的 mutations
26
20
const mutations = {
27
21
INCREMENT (state ) {
28
22
state .count ++
@@ -31,30 +25,25 @@ const mutations = {
31
25
state .count --
32
26
}
33
27
}
34
- ```
35
-
36
- ### 定义可被调用的 Actions
37
28
38
- ``` js
39
- const actions = {
40
- increment : ' INCREMENT ' ,
41
- decrement : ' DECREMENT '
42
- }
29
+ // 创建 store 实例
30
+ export default new Vuex . Store ( {
31
+ state ,
32
+ mutations
33
+ })
43
34
```
44
35
45
- ### 创建 Store 实例
36
+ ### Actions
46
37
47
38
``` js
48
- export default new Vuex .Store ({
49
- state,
50
- mutations,
51
- actions
52
- })
39
+ // actions.js
40
+ export const increment = ({ dispatch }) => dispatch (' INCREMENT' )
41
+ export const decrement = ({ dispatch }) => dispatch (' DECREMENT' )
53
42
```
54
43
55
44
### 在 Vue 组件里使用
56
45
57
- ** Template **
46
+ ** 模板 **
58
47
59
48
``` html
60
49
<div >
@@ -64,29 +53,36 @@ export default new Vuex.Store({
64
53
</div >
65
54
```
66
55
67
- ** Script **
56
+ ** 代码 **
68
57
69
58
``` js
70
- import store from ' ./store.js'
71
-
72
- export default {
73
- computed: {
74
- // 在 computed 属性内绑定 state
75
- count () {
76
- return store .state .count
59
+ // 仅需要在根组件中注入 store 实例一次即可
60
+ import store from ' ./store'
61
+ import { increment , decrement } from ' ./actions'
62
+
63
+ const app = new Vue ({
64
+ el: ' #app' ,
65
+ store,
66
+ vuex: {
67
+ getters: {
68
+ count : state => state .count
69
+ },
70
+ actions: {
71
+ increment,
72
+ decrement
77
73
}
78
- },
79
- methods: {
80
- increment: store .actions .increment ,
81
- decrement: store .actions .decrement
82
74
}
83
- }
75
+ })
84
76
```
85
77
86
- 你会注意到组件本身非常简单:它所做的仅仅是绑定到 state、然后在用户输入时调用 actions.
78
+ 你会注意到组件本身非常简单:它所做的仅仅是绑定到 state、然后在用户输入时调用 actions。
87
79
88
80
你也会发现整个应用的数据流是单向的,正如 Flux 最初所定义的那样:
89
81
82
+ 1 . 用户在组件中的输入操作触发 action 调用;
83
+ 2 . Actions 通过分发 mutations 来修改 store 实例的状态;
84
+ 3 . Store 实例的状态变化反过来又通过 getters 被组件获知。
85
+
90
86
<p align =" center " >
91
87
<img width =" 700px " src =" vuex.png " >
92
88
</p >
0 commit comments