我在 Vue.js 2.0 中制作了一个组件删除 sweetalert 的内容。它看起来像这样:
export default {
props:['service', 'method', 'id'],
methods: {
destroy() {
swal({
title: 'Weet u het zeker?',
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Ja verwijder',
cancelButtonText: 'Stop!',
confirmButtonColor: '#34495e',
cancelButtonColor: '#ff3860',
}).then (() => {
this.service[this.method](this.id)
.then(() => {
swal({
title: 'Verwijderd',
text: 'Succesvol verwijderd',
type: 'success',
showConfirmButton: false,
timer: 2000
});
location.reload();
})
.catch(() => {
swal({
title: 'Fout',
text: 'Heeft u voldoende rechten?',
type: 'error',
showConfirmButton: false,
timer: 2000
});
});
})
}
}
}
问题在于:
this.service[this.method](this.id)
不工作。我像这样传递 Prop :
<destroy :service="Service" method="destroy" :id="relation.id"></destroy>
服务类中的destroy方法如下所示:
destroy(id) {
return axios.delete('/relaties/' + id);
}
在我的 vue 调试栏中,销毁组件如下所示:
我的控制台中的错误:
Uncaught (in promise) TypeError: Cannot read property 'then' of undefined
at eval (eval at ./node_modules/babel-loader/lib/index.js?{"cacheDirectory":true,"presets":[["env",{"modules":false,"targets":{"browsers":["> 2%"],"uglify":true}}]]}!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./resources/assets/js/components/shared/Destroy.vue (app.js?id=d89bceb…:319), <anonymous>:27:54)
at <anonymous>
知道如何解决这个问题吗?
最佳答案
export default {
props:['service', 'method', 'id'],
methods: {
destroy() {
var self = this;
swal({
title: 'Weet u het zeker?',
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Ja verwijder',
cancelButtonText: 'Stop!',
confirmButtonColor: '#34495e',
cancelButtonColor: '#ff3860',
}).then (() => {
self.service[self.method](self.id)
.then(() => {
swal({
title: 'Verwijderd',
text: 'Succesvol verwijderd',
type: 'success',
showConfirmButton: false,
timer: 2000
});
location.reload();
})
.catch(() => {
swal({
title: 'Fout',
text: 'Heeft u voldoende rechten?',
type: 'error',
showConfirmButton: false,
timer: 2000
});
});
})
}
}
}
您应该创建到“this”变量的全局链接,在 SWAL 回调函数中“this”被本地 SWAL 变量替换。
关于javascript - Vue.js 调用组件中服务的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45008636/