@@ -49,10 +49,13 @@ vuex 是什么,怎么搭,以及 要有用什么角度来理解这个插件
49
49
> 3 . actions (动作),用户在 视图 上的输入引起状态的更改的可能方式。
50
50
51
51
52
- # 问题 : vuex,action ,mutations 做什么用的?
52
+ # 观念讲解 : vuex,action ,mutations 做什么用的?
53
53
54
+ > 同步:当函数执行时,就得到结果,那这个函数就是同步的。
55
+ > 异步:当函数执行时,不会马上有结果,甚至有时间差的问题,那这个函数就是异步的。
54
56
55
- ## (1) state
57
+
58
+ ## 观念讲解 : vuex,action ,mutations 做什么用的? (1) state
56
59
57
60
> 中文翻译成「状态」,建议尽量用 state 这个单字来阅读 vuex 文檔,不然你脑海一直出现状态状态状态,反而会卡死。
58
61
@@ -64,33 +67,77 @@ vuex 是什么,怎么搭,以及 要有用什么角度来理解这个插件
64
67
}
65
68
```
66
69
67
- ## (2) mutation
70
+ ## 观念讲解 : vuex,action ,mutations 做什么用的? (2) mutation
68
71
69
72
> 更改 Vuex 的 store 中的 state 的唯一方法是提交 mutation。
70
73
71
- > mutation,会与插件 devtools 协作,当 mutation 有变化时, 就做 state 的纪录,来协助开发者 debug,所以这里的代码要求同步 ,以便插件来调试。
74
+ > mutation,会与插件 devtools 协作,当 mutation 有变化时, 就做 state 的纪录,来协助开发者 debug,所以这里的函数要求同步 ,以便插件来调试。
72
75
73
76
74
77
> 来源:https://vuex.vuejs.org/zh-cn/mutations.html
75
78
79
+ ``` js
80
+ // 建议把此区当做事件注册来看(同步不是马上执行的意思,而是在当函数执行时,就得到结果)
81
+ const mutations = {
82
+ increment (state ) {
83
+ state .count ++
84
+ },
85
+ decrement (state ) {
86
+ state .count --
87
+ }
88
+ }
89
+
90
+ ```
91
+
92
+ ## 观念讲解 : vuex,action ,mutations 做什么用的?(3) Action
76
93
77
- ## (3) Action 类似于 mutation,不同在于:
94
+ > 类似于 mutation,不同在于:
78
95
79
96
> Action 提交的是 mutation(让 mutation 处理插件的调试工作 ),而不是直接变更 state 。
80
97
81
- > Action 可以包含任意异步操作 。
98
+ > Action 的函数可以包含任意异步操作,但永远只提交 mutation 。
82
99
83
100
> 来源:https://vuex.vuejs.org/zh-cn/actions.html
84
101
102
+ ``` js
85
103
104
+ const actions = {
105
+ increment: ({
106
+ commit
107
+ }) => commit (' increment' ),
108
+ decrement: ({
109
+ commit
110
+ }) => commit (' decrement' ),
111
+ incrementIfOdd ({
112
+ commit,
113
+ state
114
+ }) {
115
+ if ((state .count + 1 ) % 2 === 0 ) {
116
+ commit (' increment' )
117
+ }
118
+ },
119
+ incrementAsync ({
120
+ commit
121
+ }) {
122
+ return new Promise ((resolve , reject ) => {
123
+ setTimeout (() => {
124
+ commit (' increment' )
125
+ resolve ()
126
+ }, 1000 )
127
+ })
128
+ }
129
+
130
+ ` ` `
86
131
87
132
88
133
89
134
90
135
91
136
92
- > ### Vuex 观念 demo
137
+ ### Vuex 观念 demo
138
+
93
139
> - demo https://bhnddowinf.github.io/bhnddowinf/vuejs2demo/vuex01.html
140
+
94
141
> - 源码 https://github.com/bhnddowinf/vuejs2-learn/blob/master/my-project/src/vuex-demo/v01_app.js
95
142
> - 源码 https://github.com/bhnddowinf/vuejs2-learn/blob/master/my-project/src/vuex-demo/v01.vue
96
143
0 commit comments