首页 > 解决方案 > vue - 如何将回调传递给 vuex 操作

问题描述

我正在考虑如何将回调传递给 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
};

应用程序.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>

标签: javascripthtmlcssvue.jsvuex

解决方案


问题发生在两个地方:

  1. 您商店中的有效负载语法错误
  2. ()将函数传递给对象时,您将在末尾触发函数:

解决有效载荷问题

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

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

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

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

推荐阅读