Skip to content
On this page

action

Action 类似于 mutation,不同在于:

  • Action 提交的是 mutation,而不是直接变更状态;
  • Action 可以包含任意异步操作;

这里有一个非常重要的参数 context:

  • context 是一个和 store 实例均有相同方法和属性的 context 对象;
  • 所以我们可以从其中获取到 commit 方法来提交一个 mutation,或者通过 context.state 和 context.getters 来 获取 state 和 getters;
  • 但是为什么它不是 store 对象呢?这个等到我们讲 Modules 时再具体来说;
javascript
mutations: {
    increment(state) {
        state.counter++
    }
},
actions: {
    increment(context) {
        context.commit("mincrement")
    }
}
1
2
3
4
5
6
7
8
9
10

actions 的分发操作

如何使用 action 呢?进行 action 的分发: 分发使用的是 store 上的 dispatch 函数;

javascript
add(){
    this.$store.dispatch('increment')
}
1
2
3

同样的,它也可以携带我们的参数:

javascript
add(){
    this.$store.dispatch('increment',{count:100})
}
1
2
3

也可以以对象的形式进行分发:

javascript
add(){
    this.$store.dispatch({
       type: 'increment',
       count:100
    })
}
1
2
3
4
5
6

actions 的辅助函数

action 也有对应的辅助函数:

  • 对象类型的写法;
  • 数组类型的写法;

vue2

javascript
 methods: {
    ...mapActions(["incrementAction", "decrementAction"]),
    ...mapActions({
      add: "incrementAction",
      sub: "decrementAction"
    })
},
1
2
3
4
5
6
7

vue3

javascript
setup() {
    const actions = mapActions(["incrementAction", "decrementAction"])
    const actions2 = mapActions({
    add: "incrementAction",
    sub: "decrementAction"
    })

    return {
    ...actions,
    ...actions2
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
javascript
import { onMounted } from "vue";
import { useStore } from 'vuex'

export default {
setup() {
    const store = useStore()
        onMounted(() => {
            const promise = store.dispatch("getHomeMultidata")
            promise.then(res => {
                console.log(res)
            }).catch(err => {
                console.log(err)
            })
        })
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

actions 的异步操作

Action 通常是异步的,那么如何知道 action 什么时候结束呢? 我们可以通过让 action 返回 Promise,在 Promise 的 then 中来处理完成后的操作;

javascript
{
    actions: {
        increment (context) {
            return new Promise( (reso lve) =>{
                setTimeout(() =>{
                    context.commit(" increment")
                    resolve("异步完成"
                }, 1000)
            })
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
javascript
const store = usestore();
const increment = () => {
    store.dispatch("increment").then(res =>
        console.1og(res"异步完成");
    })
}
1
2
3
4
5
6
沪ICP备20006251号-1