vue - 如何将回调传递给 vuex 操作

vue - how to pass callback to vuex action

我正在研究如何将回调传递给 vuex 操作

我试过下面的代码但没有用。触发前的代码运行

src/store/modules/web3.module.js

import Web3 from "web3";

const state = {};

const getters = {};

const mutations = {};

const actions = {
  async test(context, confirmCallback, rejectCallback) {
    confirmCallback();
    rejectCallback();
  }
};

export default {
  state,
  getters,
  actions,
  mutations
};

App.vue

<template>
  <div id="app"></div>
</template>

<script>
import { mapActions } from "vuex";

export default {
  name: "App",
  methods: {
    ...mapActions(["test"]),
    onModalOpen() {
      console.log("open");
    },
    onModalClose() {
      console.log("Close");
    },
  },
  async created() {
    let result = await this.test({
      confirmCallback: this.onModalOpen(),
      rejectCallback: this.onModalClose(),
    });
  },
};
</script>

问题发生在两个地方:

  1. 您商店中的负载语法错误
  2. 当通过一个对象传递函数时,你正在触发最后带有 () 的函数:

解决负载问题

一个动作有 2 个参数,第一个是上下文,它是一个包含状态、突变等的对象。然后是有效载荷,它也是一个对象

const actions = {
  async test(context, {confirmCallback, rejectCallback}) {
    confirmCallback();
    rejectCallback();
  }
}

解决减速问题 要解决 decleration 问题,只需删除末尾的 (),如下所示:

  async created() {
    let result = await this.test({
      confirmCallback: this.onModalOpen,
      rejectCallback: this.onModalClose,
    });
  },