element-plus Message Box 消息弹窗组件 捕获异常

706 阅读1分钟

你是否遇到过,使用ElMessageBox.confirm组件时,当接口报错的时候,弹出两个提示?

what.jpg

废话不说,上图 👇

17cb485672b275b8df5d73c43d26b6e.png

代码如下
     ElMessageBox.confirm('是否删除该条数据', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
          // 当该接口报错时,也会走下面的catch
            await delData(ids)
          })
          .catch(() => {
            ElMessage({
              type: 'error',
              message: '取消成功'
            })
          })

优化代码如下(解决)
     ElMessageBox.confirm('是否删除该条数据', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
          // 在这里捕获一下异常,就不会走下面的catch,因此不会弹下面的提示框
           try {
              await delData(ids)
            } catch {}
          })
          .catch(() => {
            ElMessage({
              type: 'error',
              message: '取消成功'
            })
          })