我在vue组件中有一个评论删除按钮。
fs.open()
单击按钮时将调用方法“destroy”
<button class="button" style="background-color: grey;" @click="destroy">Delete</button>
我预计当警报出来时,如果用户点击确认按钮然后进行删除,但看起来当用户点击删除功能时不会执行。这有什么问题?
答案 0 :(得分:2)
SWAL回调函数中的this
上下文是SWAL实例,而不是Vue实例!这意味着this.comment.id
和this.$el
可能是undefined
,因此,该功能不会执行,并会产生TypeError。
要解决此问题,
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.'));
})