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

Vue.js中Sweetalert2删除确认后Axios请求未执行问题排查

解决Vue.js中Sweetalert2确认后Axios请求不执行的问题

我猜你的destroy方法大概率是在Sweetalert2的回调逻辑里出了问题——要么是请求写在了弹窗外部(导致弹窗一弹出来就执行,不是用户确认后执行),要么是回调里的this指向不对,让Axios请求没触发。咱们一步步来修复:

1. 先看看你可能踩的坑

你之前的代码可能是这两种问题情况:

情况一:请求写在弹窗外部,没等用户确认就执行

destroy(id) {
  Swal.fire({
    title: 'Are you sure?',
    text: "You won't be able to revert this!",
    icon: 'warning',
    showCancelButton: true,
    confirmButtonText: 'Yes, Delete it!'
  })
  // 这里的请求会在弹窗弹出时立刻执行,根本不等用户确认
  axios.delete(`/api/statuses/${id}`)
}

情况二:回调里this丢失,导致请求逻辑失效

destroy(id) {
  Swal.fire({/* 弹窗配置 */})
  .then(function(result) {
    if (result.isConfirmed) {
      // 这里的this不是Vue组件实例,要是你用了this.$store或者this.xxx就会报错
      axios.delete(`/api/statuses/${id}`)
    }
  })
}

2. 正确的两种写法

方案一:用async/await(逻辑更清晰)

async destroy(id) {
  // 先弹出确认框,等待用户操作
  const confirmResult = await Swal.fire({
    title: 'Are you sure?',
    text: "You won't be able to revert this!",
    icon: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#d33',
    cancelButtonColor: '#3085d6',
    confirmButtonText: 'Yes, Delete it!'
  })

  // 只有用户点击确认后,才执行删除请求
  if (confirmResult.isConfirmed) {
    try {
      await axios.delete(`/api/statuses/${id}`)
      // 请求成功后的操作:比如提示成功、刷新列表
      Swal.fire('Deleted!', 'Your data has been removed.', 'success')
      this.fetchStatuses() // 假设这是你刷新列表的方法
    } catch (err) {
      // 请求失败的兜底提示
      Swal.fire('Oops!', 'Failed to delete the data.', 'error')
    }
  }
}

方案二:用Promise回调+箭头函数(保留this指向)

如果不想用async/await,用箭头函数就能确保回调里的this还是Vue组件实例:

destroy(id) {
  Swal.fire({
    title: 'Are you sure?',
    text: "You won't be able to revert this!",
    icon: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#d33',
    cancelButtonColor: '#3085d6',
    confirmButtonText: 'Yes, Delete it!'
  }).then((result) => {
    // 箭头函数让this指向Vue组件,不会丢失上下文
    if (result.isConfirmed) {
      axios.delete(`/api/statuses/${id}`)
        .then(res => {
          // 成功后更新本地数据,不用刷新页面
          this.statuses = this.statuses.filter(item => item.id !== id)
          Swal.fire('Deleted!', 'Your data has been removed.', 'success')
        })
        .catch(err => {
          Swal.fire('Oops!', 'Failed to delete the data.', 'error')
        })
    }
  })
}

3. 你的按钮代码可以保持不变

<button @click="destroy(statuses.id)" class="btn btn-danger btn-flat btn-sm">
  <i class="fa fa-remove"></i> Delete
</button>

这样修改后,用户点击弹窗的"Yes, Delete it!"按钮时,Axios请求就会正常触发啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:39:15