如何检索发送回 SweetAlert2 Ajax 调用的数据?

How do I retrieve the datas sent back to a SweetAlert2 Ajax call?

我正在建立一个网站并专门使用 SweetAlert2 作为我的确认方法(成功、编辑或删除的通知)。

由于它需要很多行,所以我决定在一个 JS 文件中设置与 SweetAlert 相关的所有内容,我将调用并作为函数使用,如下所示:

// src/config/SweetAlert.js

import swal from 'sweetalert2'
import 'sweetalert2/src/sweetalert2.scss'
import axios from 'axios'

const API = axios.create({
  baseURL: 'http://localhost:3333/api/v1'
})

const SweetAlert = {
  delete (title, text, type, confirmation, url) {
    swal({
      title: title,
      text: text,
      type: type,
      showCancelButton: true,
      showLoaderOnConfirm: true,
      confirmButtonText: 'Delete',
      preConfirm: () => {
        return API.delete(url)
          .then(response => {
            return response
          })
      },
      allowOutsideClick: () => !swal.isLoading()
    }).then((result) => {
      if (result.value) {
        swal({
          type: 'success',
          title: confirmation
        })
      }
    })
  },

  // Some other possibilities
}

export default SweetAlert

而我是这样使用的:

// some methods
handleDelete (post, index) {
  const result = SweetAlert.delete(
    `Delete "${post.title}"?`,
    `Are you sure you want to delete "${post.tite}"?`,
    'warning',
    `"${post.title}" was successfully deleted`,
    `/post/${post.id}`
  )
}

在从列表中删除已删除的元素之前,我想确保我的 API 一切顺利。我尝试添加 return result.value 因为有以下代码块:

if (result.value) {
  swal({
    type: 'success',
    title: confirmation
  })
  // Returns undefined as soon as SweetAlert shows up
  return result.value
  // shows up only when I click "Delete" on the Swal modal, has the infos I need
}

我尝试将我的代码更改为以下内容:

const result = SweetAlert.delete(  // my initial code )

if (result.data === 'ok') {
    this.posts.splice(index, 1) 
}

但我得到的只是"undefined"。

有没有办法检索这种数据?

提前致谢

Swal returns 一个 Promise,所以在你的 delete 函数中像这样使用它:

delete (title, text, type, confirmation, url) {
    let res = swal({
      // your code here ...
    });
    res.then(result => {
      // your code here ...
    })
    return res;
)

之后你可以这样使用它:

SweetAlert.delete(  // my initial code )
    .then(result => {
        if (result.value) {
            this.posts.splice(index, 1);
        }
    })
    .catch(error => {
        console.log('error', error)
    })