You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让clickMethod在Promise返回结果后执行后续条件判断?

解决异步确认弹窗的后续逻辑执行问题

要让条件判断在Promise返回结果后再执行,需要做两处关键修改:

1. 让showBoxConfirm返回Promise对象

原函数没有返回弹窗的Promise实例,导致调用时无法获取异步结果。修改后让函数返回this.$bvModal.msgBoxConfirm的Promise链,并在catch中统一返回false(处理用户取消/关闭弹窗的情况):

<script>
export default {
  methods: {
    // ...其他方法
    showBoxConfirm() {
      const h = this.$createElement;
      const titleVNode = h("div", {domProps: {innerHTML: "Title from <i>HTML<i> string"}});
      const messageVNode = h("div", {class: ["foobar"]}, [
        h("b-img", {
          props: {
            src: "https://picsum.photos/id/20/250/250",
            thumbnail: true,
            center: true,
          },
        }),
        h("p", {class: ["text-center"]}, [
          "Question text?",
        ]),
      ]);
      // 返回Promise,让调用者可等待结果
      return this.$bvModal
        .msgBoxConfirm([messageVNode], {
          title: [titleVNode],
          size: "sm",
          buttonSize: "sm",
          okVariant: "danger",
          okTitle: "YES",
          cancelTitle: "NO",
          footerClass: "p-2",
          hideHeaderClose: false,
          centered: true,
        })
        .then((value) => {
          // 用户点击确认,返回true
          return value;
        })
        .catch((err) => {
          // 用户取消/关闭弹窗,返回false
          return false;
        });
    },
  },
};
</script>

2. 在clickMethod中等待异步结果

使用async/await语法(最直观的方式),将clickMethod声明为异步函数,等待showBoxConfirm返回结果后再执行条件判断:

<script>
export default {
  methods: {
    async clickMethod() {
      // 等待弹窗的异步结果返回
      const result = await this.showBoxConfirm();
      // 结果为false时终止函数
      if (!result) return;

      // 此处编写用户确认后的后续逻辑
      console.log("用户确认,执行后续操作");
    },
    // ...其他方法
  },
};
</script>

替代方案:使用then回调

如果不想用async/await,也可以通过then回调处理结果:

clickMethod() {
  this.showBoxConfirm().then(result => {
    if (!result) return;
    // 用户确认后的后续逻辑
    console.log("用户确认,执行后续操作");
  });
}

内容的提问来源于stack exchange,提问作者oguzcan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 07:05:21