问题描述
我正在尝试使用sweetalert在vue.js中编写对Websocket消息的响应的代码。
可悲的是,我无法调用sweetalert或在我创建的onmessage中的方法中定义的函数。
未捕获的TypeError:this.confirmation不是函数 在WebSocket.connection.onmessage
methods: {
confirmation(response) {
if (response.data == "stop") {
this.$swal({
icon: "success",text: "stopped!",});
}
if (response.data == "start") {
this.$swal({
icon: "success",text: "started!",});
}
},},created() {
this.connection.onmessage = function(event) {
console.log(event.data);
this.confirmation(event);
};
},
解决方法
我认为这与this
的使用有关,因为似乎在错误的上下文中调用了您的方法。 Details on the usage of this in js here。
我可能只是在其他地方定义函数,而无需使用this
就可以在其中访问它。也许有一种更优雅的方法,但是老实说,我不熟悉javascript的深入知识
虽然@Neferin 的回答通常是正确的,但您可以使用 arrow function 来处理这样的情况。很快,用 function
关键字定义的函数有它自己的作用域,意味着有它自己的 this
。箭头函数没有作用域。
这是一个例子:
created() {
this.connection.onmessage => (event) {
// ^^^^
// in the arrow function this is a parent scope
console.log(event.data);
this.confirmation(event);
};
},