我在 vue 组件中有一个注释删除按钮。
<button class="button" style="background-color: grey;" @click="destroy">Delete</button>
当按钮点击时将调用该方法"破坏">
destroy(){
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(){
axios.delete('/comment/' + this.comment.id + '/delete');
$(this.$el).fadeOut(300, () => {
return toastr.success('Comment deleted.');
});
});
},
我希望当警报出现时,如果用户单击确认按钮然后处理删除,但似乎当用户单击删除功能时不会执行。这里有什么问题?
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.')); })
这不仅是此上下文错误。 SweetAlert 是基于 promise 的,所以你需要在 Promise.prototype.then(( 方法中调用你的 axios 请求。
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
})
.then( () => {
axios.delete('/comment/' + this.comment.id + '/delete');
$(this.$el).fadeOut(300, () => toastr.success('Comment deleted.'));
})