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

时间:2018-10-23 11:48:50

标签: vue.js sweetalert2

我正在建立一个网站,并专门使用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) 
}

但是我得到的只是“未定义”。

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

提前谢谢

1 个答案:

答案 0 :(得分:1)

Swal返回一个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)
    })