【问题标题】:How do I retrieve the datas sent back to a SweetAlert2 Ajax call?如何检索发送回 SweetAlert2 Ajax 调用的数据?
【发布时间】:2018-10-23 11:48:50
【问题描述】:

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

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

// 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) 
}

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

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

提前谢谢你

【问题讨论】:

    标签: vue.js sweetalert2


    【解决方案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)
        })
    

    【讨论】:

    • 谢谢,比我想象的要容易,但是我没有想到这种可能性,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    • 2023-03-10
    相关资源
    最近更新 更多