在Vue js中删除带有Sweet警报的确认

时间:2017-08-26 03:37:31

标签: javascript vue.js

我在vue组件中有一个评论删除按钮。

fs.open()

单击按钮时将调用方法“destroy”

<button class="button" style="background-color: grey;" @click="destroy">Delete</button>

我预计当警报出来时,如果用户点击确认按钮然后进行删除,但看起来当用户点击删除功能时不会执行。这有什么问题?

1 个答案:

答案 0 :(得分:2)

SWAL回调函数中的this上下文是SWAL实例,而不是Vue实例!这意味着this.comment.idthis.$el可能是undefined,因此,该功能不会执行,并会产生TypeError

要解决此问题,

  • 使用Arrow Functions

    swal({
      title: "Delete this comment?",
      text: "Are you sure? You won't be able to revert this!",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#3085d6",
      confirmButtonText: "Yes, Delete it!",
      closeOnConfirm: true
    }, () => {
      axios.delete('/comment/' + this.comment.id + '/delete');
      $(this.$el).fadeOut(300, () => toastr.success('Comment deleted.'));
    })
    
  • 捕获this

    let inst = this;
    swal({
      title: "Delete this comment?",
      text: "Are you sure? You won't be able to revert this!",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#3085d6",
      confirmButtonText: "Yes, Delete it!",
      closeOnConfirm: true
    }, function onDelete(){
      axios.delete('/comment/' + inst.comment.id + '/delete');
      $(inst.$el).fadeOut(300, () => toastr.success('Comment deleted.'));
    })