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

Vue中SweetAlert确认后调用deleteRecord报undefined错误如何解决

错误原因

你的代码报错是因为prepareRemove方法中,Swal.fire的then回调使用了普通函数声明,普通函数的this指向调用它的上下文,在这个异步回调里this不会指向Vue组件实例,因此无法读取到实例上的deleteRecord方法。

修复方案

方案1:将回调改为箭头函数(推荐)

箭头函数会继承外层作用域的this指向,不需要额外处理上下文,修改后的prepareRemove代码如下:

prepareRemove(id){
  const removeId = id;
  Swal.fire({
    title: '您确定吗',
    text: "您要删除这条记录吗?",
    type: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#d33',
    cancelButtonColor: '#3085d6',
    confirmButtonText: '是的,删除!',
    cancelButtonText: '取消',
    buttonsStyling: true
  }).then((isConfirm) => {
    if(isConfirm.value === true) {
      this.deleteRecord(removeId);
    }
  });
}

方案2:提前存储组件实例指向

和你现有deleteRecord方法的处理逻辑一致,在方法顶部先存储当前Vue实例的this指向,回调内用存储的变量调用方法:

prepareRemove(id){
  const self = this;
  const removeId = id;
  Swal.fire({
    title: '您确定吗',
    text: "您要删除这条记录吗?",
    type: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#d33',
    cancelButtonColor: '#3085d6',
    confirmButtonText: '是的,删除!',
    cancelButtonText: '取消',
    buttonsStyling: true
  }).then(function (isConfirm) {
    if(isConfirm.value === true) {
      self.deleteRecord(removeId);
    }
  });
}

两种方案任选其一修改即可解决当前报错。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 04:24:00