网站搜索

javascript - 有没有办法为 ui-element 的 ElMessageBox 确认按钮添加点击事件?


当我从表格中删除一条数据时,我希望先在屏幕中间弹出一个警告。删除功能已经准备好了,我只是想在弹出 ElMessageBox 时添加确认按钮的点击事件(删除功能)。当我按下“是”时,应该执行删除操作。但我找不到方法。有人能帮忙吗?提前感谢!

这是我的 HTML 代码

              <el-button class="menu-link px-3" type="text" @click="open">
            <span class="svg-icon svg-icon-3">
              <inline-svg src="media/icons/duotune/art/art005.svg" /> </span
            >&nbsp;Delete
          </el-button>

这是我的脚本代码

   const open = () => {
    ElMessageBox.confirm(
'Do you want to continue the deletion?',  
{
  confirmButtonText: 'Yes',
  cancelButtonText: 'No',
  type: 'warning',
  center: true,     
})
.then(() => {
  ElMessage({
    type: 'success',
    message: 'Deletion completed',
  })
})
.catch(() => {
  ElMessage({
    type: 'info',
    message: 'Deletion canceled',
  })
})
}

这是我的删除功能

    const deleteCustomer = (id) => {
  for (let i = 0; i < tableData.value.length; i++) {
    if (tableData.value[i].id === id) {
      tableData.value.splice(i, 1);
    }
  }
};

你可以点击查看屏幕截图输出

答案#1

当你点击是时,open 函数的 .then() 部分会被执行。在该代码块中,你需要调用删除函数。

你也需要将 id 传递给 open() 函数。像 open(id) 这样。

this.deleteCustomer(id) 或者只是 deleteCustomer(id)。

const open = (id) => { // pass the id
    ElMessageBox.confirm(
'Do you want to continue the deletion?',  
{
  confirmButtonText: 'Yes',
  cancelButtonText: 'No',
  type: 'warning',
  center: true,     
})
.then(() => {
  // here you can call the delete function. 
  // this is the part that is executed when you click yes
  this.deleteCustomer(id) // use the id
  ElMessage({
    type: 'success',
    message: 'Deletion completed',
  })
})
.catch(() => {
  ElMessage({
    type: 'info',
    message: 'Deletion canceled',
  })
})
}