-
Notifications
You must be signed in to change notification settings - Fork 1
Actions
Actions are used to update the module state, it can be a normal function or an asynchronous function:
Actions 是用于更新 module state
的地方, 可以是普通函数, 也可以是异步函数:
const moduleB = {
namespace: 'moduleb',
state: {
title: 'the title of moduleB',
desc: 'some description for moduleB'
},
actions: {
changeTitle(state, payload){
// print old title
console.log(state.title);
const {title} = payload;
return Object.assign({}, state, {
title
});
},
async changeDesc(state, payload){
const desc = await Promise.resolve('new description for moduleB');
return {
desc
}
}
}
}
Action function to accept a state parameter and payload parameter, state
is the current module
state, payload
is the caller passed to the Action function parameters. Action return value is an object, this object can be a new state
object or part of the state
object that needs to be updated.
Action 函数接受一个 state
参数和 payload
参数, state
是 module
当前的状态, payload
是调用者传递给 Action 函数的参数. Action 的返回值是一个对象, 这个对象可以是一个新的 state
对象或者需要被更新的 state
对象的一部分.
In vue components, it needs to use mergeActions
helper which maps component methods to module.actions[action]
calls (requires modules injection):
在 Vue 组件中, 需要使用 mergeActions
辅助函数将组件的 methods
映射为 module.actions[action]
调用(需要先在 Vue 实例中注入 modules
):
import { mergeActions } from 'revuejs';
export default {
// ...
methods: {
...mergeActions([
// map `this.changeTitle()` to `modulea.actions['changeTitle']()`
// 映射 this.changeTitle() 为 modulea.actions['changeTitle']()
'moduleb.changeTitle'
]),
...mergeActions({
// map `this.updateTitle()` to `modulea.actions['changeTitle']()`
// 映射 this.updateTitle() 为 modulea.actions['changeTitle']()
updateTitle: 'moduleb.changeTitle'
})
}
}
When an Action depends on the return of another Action data, if we make use of async/await , a JavaScript feature landing very soon, we can compose our actions like this:
当某个 Action 依赖于另一个 Action 的返回数据时, 利用 async/await 可以按照下面的方式来组合使用 Actions:
// ...
actions: {
async changeTitle(state, payload){
const {title} = payload;
const {desc} = await this.actions.changeDesc(state, payload);
return Object.assign({}, state, {
title,
desc
});
},
async changeDesc(state, payload){
const desc = await Promise.resolve('new description for moduleA');
return {
desc
}
}
}
// ...