@@ -132,3 +132,68 @@ const vm = new Vue({
132132 }
133133})
134134```
135+
136+ ### 管理多模块 Actions
137+
138+ 通常在大型 App 中,action 应该按不同目的进行 分组 / 模块化 管理,例如,userActions 模块用于处理用户注册、登录、注销,而 shoppingCartActions 处理购物任务。
139+
140+ 当想要在不同组件中仅引入必需的 action 时,模块化使之更为方便。
141+
142+ 你还可以在 action 模块中引入其他 action 模块来实现复用。
143+
144+ ``` javascript
145+ // errorActions.js
146+ export const setError = ({dispatch}, error ) => {
147+ dispatch (' SET_ERROR' , error)
148+ }
149+ export const showError = ({dispatch}) => {
150+ dispatch (' SET_ERROR_VISIBLE' , true )
151+ }
152+ export const hideError = ({dispatch}) => {
153+ dispatch (' SET_ERROR_VISIBLE' , false )
154+ }
155+ ```
156+
157+ ``` javascript
158+ // userActions.js
159+ import {setError , showError } from ' ./errorActions'
160+
161+ export const login = ({dispatch}, username , password ) => {
162+ if (username && password) {
163+ doLogin (username, password).done (res => {
164+ dispatch (' SET_USERNAME' , res .username )
165+ dispatch (' SET_LOGGED_IN' , true )
166+ dispatch (' SET_USER_INFO' , res)
167+ }).fail (error => {
168+ dispatch (' SET_INVALID_LOGIN' )
169+ setError ({dispatch}, error)
170+ showError ({dispatch})
171+ })
172+ }
173+ }
174+
175+ ```
176+
177+ 当从一个模块中调用另一个模块的 action 时,或者调用同一模块中的另一个 action 时,切记,action 的第一个参数是 store 实例,因此应该将调用者 action 的第一个参数传递给被调用 action。
178+
179+ 如果你使用 ES6 的解构形式来编写 action,确保调用者 action 的第一个参数包含两个 action 中用到的所有属性和方法。举例说明,调用者 action 仅使用 * dispatch* 方法,而被调用 action 使用了 * state* 属性和 * watch* 方法,那么,* dispatch* 、* state* 和 * watch* 应该都出现在传递给调用者 action 的第一个形式参数中,示例如下:
180+
181+ ``` javascript
182+ import {callee } from ' ./anotherActionModule'
183+
184+ export const caller = ({dispatch, state, watch}) {
185+ dispatch (' MUTATION_1' )
186+ callee ({state, watch})
187+ }
188+ ```
189+
190+ 或者,你也可以使用老式的函数语法:
191+
192+ ``` javascript
193+ import {callee } from ' ./anotherActionModule'
194+
195+ export const caller = (store) {
196+ store .dispatch (' MUTATION_1' )
197+ callee (store)
198+ }
199+ ```
0 commit comments